﻿using AutoMapper;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.IT;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.Entity.View;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_PackListBusiness : BaseBusiness<PB_PackList>, IPB_PackListBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IMapper _mapper;
        readonly IOperatorDept _odept;
        public PB_PackListBusiness(IDbAccessor db, IOperator @operator, IMapper mapper, IOperatorDept @odept)
            : base(db)
        {
            _operator = @operator;
            _mapper = @mapper;
            _odept = @odept;
        }

        #region 外部接口

        public async Task<PageResult<PB_PackList>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_PackList>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PackList, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            where = where.And(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_PackList> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_PackList data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_PackList data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            if (await Db.GetIQueryable<PB_PackListInfo>().AnyAsync(x => ids.Contains(x.PackId)))
            {
                throw new BusException("删除失败！该信息存在数据禁止删除！");
            }
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 生成包编号
        /// </summary>
        /// <param name="userqrcode">操作人</param>
        /// <param name="PackageType">是否标准包</param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task<PB_PackList> GetPackListNumberAsync(string userqrcode, int PackageType, MongoDBOptions _mongodbOptions)
        {
            //解析用户二维码
            string[] usermodel = userqrcode.Split(',');
            PB_PackList pbdata = new PB_PackList();
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
            string dataName = "bag_" + sjtime;
            string dataId = IdHelper.GetId();
            pbdata.Id = dataId;
            pbdata.DeptId = _operator?.Property.DepartmentId;
            pbdata.BoxNo = dataName;
            pbdata.QrCode = h_Pack + "," + dataId;
            pbdata.Type = 1;
            pbdata.CreatorId = usermodel[1].ToString();
            pbdata.CreateTime = DateTime.Now;
            pbdata.CreatorName = _operator?.Property?.RealName;
            pbdata.Status = 0;
            pbdata.PackageType = PackageType == 1 ? 1 : 0;
            pbdata.IsUnpacking = false;
            await InsertAsync(pbdata);
            //PrintQueue pq = new PrintQueue();
            //pq.Id = IdHelper.GetId();
            //pq.No = sjtime;
            //pq.Name = dataName;
            //pq.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            //pq.QrCode = h_Pack + "," + dataId;
            //pq.Type = Skill_Type.Package.ToString();
            //pq.TypeName = "";
            //pq.Dept = _operator?.Property?.DepartmentName;
            //pq.Status = "0";
            //插入mongo队列
            //MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //await mongo.AddAsync<PrintQueue>(PrintQueueCollection, pq);
            var q = GetIQueryable().Where(x => x.Id == dataId);
            return await q.FirstOrDefaultAsync();
        }

        /// <summary>
        /// 通知入库
        /// </summary>
        /// <param name="query">请求参数</param>
        /// 调整入库通知包名称去重   2022-03-02  赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task NoticeWarehousing(NoticeWarehousingQuery query)
        {
            //var qdata = await Db.GetListBySqlAsync<PB_PackList>("select * from PB_PackList where Id in (" + string.Format("'{0}'", string.Join(",", ids.ToArray()).Replace(",", "','")) + ")");
            //var qdata = await Db.GetIQueryable<PB_PackList>().Where(x => ids.Contains(x.Id)).ToListAsync();
            //var packlist = qdata.GroupBy(x => new { x.BoxName }).Select(x => new { BoxName = x.Key.BoxName }).ToList();
            ///*
            // * 开发人：崔楠
            // * 提交日期：2022-02-25 17:10
            // * 修改内容：插入说明字段时过滤重复物料名称
            // * 上传SVN：是
            // */
            //var qdata = await Db.GetListBySqlAsync<PB_PackList>("select distinct BoxName from PB_PackList where Id in (" + string.Join(",", ids.ToArray()) + ")");
            //var qdata = await Db.GetIQueryable<PB_PackList>().Where(x => ids.Contains(x.Id)).Select(s => s.BoxName).Distinct().ToListAsync();

            //包
            List<string> ids = new List<string>();
            //单个物料
            List<string> materids = new List<string>();
            //单个成品
            List<string> jobids = new List<string>();

            string memo = string.Empty;
            if (query.NoticeData.Count > 0)
            {
                var NoticeData = query.NoticeData.GroupBy(x => new { x.BoxName, x.Id, x.Type }).Select(x => new { Id = x.Key.Id, BoxName = x.Key.BoxName, Type = x.Key.Type }).ToList();
                foreach (var item in NoticeData)
                {
                    if (item.Type == "0")
                    {
                        ids.Add(item.Id);
                    }
                    else if (item.Type == "1")
                    {
                        materids.Add(item.Id);
                    }
                    else if (item.Type == "2")
                    {
                        jobids.Add(item.Id);
                    }
                }
                var materialnames = query.NoticeData.GroupBy(x => new { x.BoxName }).Select(x => new { BoxName = x.Key.BoxName }).ToList();
                foreach (var item in materialnames)
                {
                    memo += item.BoxName + ",";
                }
                if (memo.Length > 0)
                {
                    memo = memo.Substring(0, memo.Length - 1);
                }
            }

            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            PB_WarehousingNotice pB_WarehousingNotice = new PB_WarehousingNotice();
            string dataId = IdHelper.GetId();
            pB_WarehousingNotice.Id = dataId;
            pB_WarehousingNotice.QrCode = h_WarehousingNotice + "," + dataId;
            pB_WarehousingNotice.DeptId = bdata.DepartmentId;
            pB_WarehousingNotice.CreatorName = bdata.RealName;
            pB_WarehousingNotice.CreateTime = DateTime.Now;
            pB_WarehousingNotice.CreatorId = _operator.UserId;
            pB_WarehousingNotice.Deleted = false;
            pB_WarehousingNotice.Type = 1;
            pB_WarehousingNotice.CustomerToexamine = 1;
            pB_WarehousingNotice.Memo = memo;
            pB_WarehousingNotice.StorId = query.StorId;
            await Db.InsertAsync<PB_WarehousingNotice>(pB_WarehousingNotice);
            List<PB_Material> materlist = await Db.GetIQueryable<PB_Material>().ToListAsync();
            List<TD_RecDetail> RecDetaillist = new List<TD_RecDetail>();
            List<PB_JobNotice> JobNoticeList = new List<PB_JobNotice>();
            //汇总数量
            double? dnuns = 0;
            //汇总金额
            double? Amount = 0;
            //收货单Id
            string recid = IdHelper.GetId();
            string sqlMain = string.Empty;
            //获取成品Id
            List<string> jobid = new List<string>();
            List<JobMaterial> materiallist = new List<JobMaterial>();

            //提交包信息
            if (ids.Count > 0)
            {
                //修改包的状态
                sqlMain += @" UPDATE PB_PackList SET  Status = '2',NoticeId='" + dataId + "' WHERE id in (" + string.Format("'{0}'", string.Join(",", ids.ToArray()).Replace(",", "','")) + "); ";
                //获取包对应的成品码
                Expression<Func<PB_PackListInfo, PB_PackList, PB_JobBookingQrCode, JobMaterial>> select = (a, b, c) => new JobMaterial
                {
                    JobBookingId = a.JobBookingId,
                    JobId = c.ParentId,
                    Nums = 1,
                    MaterialId = c.MaterialId,
                    PackId = a.PackId,
                    JobMaterialId = ""
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                        join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                var listdata = await q.Where(x => ids.Contains(x.PackId)).ToListAsync();
                foreach (var item in listdata)
                {
                    JobMaterial jm = new JobMaterial();
                    jm.JobBookingId = item.JobBookingId;
                    jm.JobId = item.JobId;
                    jm.Nums = item.Nums;
                    jm.MaterialId = item.MaterialId;
                    jm.PackId = item.PackId;
                    jm.JobMaterialId = item.JobMaterialId;
                    materiallist.Add(jm);

                    jobid.Add(item.JobBookingId);
                }
                //获取报工Id
                var packjob = listdata.GroupBy(x => new { x.JobId }).Select(x => new { JobId = x.Key.JobId, Nums = x.Count() }).ToList();
                foreach (var item in packjob)
                {
                    sqlMain += @" update PB_JobBooking set Status=2,QualityUserId='" + _operator.UserId + "',QualityUserName='" + bdata.RealName + "',QualityTime=NOW(),StatisticsUserId='" + _operator.UserId + "',StatisticsUserName='" + bdata.RealName + "',ReturnNums='" + item.Nums + "',StatisticsTime=NOW(),StatisticsNums='" + item.Nums + "' where Id='" + item.JobId + "'; ";
                    // update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+" + item.Nums + ",WarehousingTime=NOW() where Id=(select ParentId from PB_JobBooking where Id='" + item.JobId + "'); 
                }

            }
            //提交单个物料
            if (materids.Count > 0)
            {
                //获取单个物料对应的成品码
                Expression<Func<PB_JobMaterial, PB_JobBookingQrCode, JobMaterial>> select = (a, b) => new JobMaterial
                {
                    JobBookingId = b.Id,
                    JobId = a.ParentId,
                    PackId = "",
                    Nums = a.Nums,
                    MaterialId = a.MaterialId,
                    JobMaterialId = a.Id
                };
                select = select.BuildExtendSelectExpre();
                var qMater = from a in Db.GetIQueryable<PB_JobMaterial>().AsExpandable()
                             join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.ParentId equals b.ParentId into ab
                             from b in ab.DefaultIfEmpty()
                             select @select.Invoke(a, b);
                var Materlistdata = await qMater.Where(x => materids.Contains(x.JobMaterialId)).ToListAsync();

                foreach (var item in Materlistdata)
                {
                    var itemdata = query.NoticeData.Where(x => x.Id == item.JobMaterialId).FirstOrDefault();
                    JobMaterial jm = new JobMaterial();
                    jm.JobBookingId = item.JobBookingId;
                    jm.JobId = item.JobId;
                    jm.Nums = itemdata == null ? item.Nums : itemdata.Nums;
                    jm.MaterialId = item.MaterialId;
                    jm.PackId = item.PackId;
                    jm.JobMaterialId = item.JobMaterialId;
                    materiallist.Add(jm);

                    jobid.Add(item.JobBookingId);

                    sqlMain += @" update PB_JobMaterial set Status='1',NoticeId='" + dataId + "',InNums=" + (itemdata == null ? item.Nums : itemdata.Nums) + " where Id='" + item.JobMaterialId + "'; ";

                }

                //获取报工Id
                var materjob = Materlistdata.GroupBy(x => new { x.JobId, x.Nums }).Select(x => new { JobId = x.Key.JobId, Nums = x.Key.Nums }).ToList();
                foreach (var item in materjob)
                {

                    sqlMain += @" update PB_JobBooking set Status=2,QualityUserId='" + _operator.UserId + "',QualityUserName='" + bdata.RealName + "',QualityTime=NOW(),StatisticsUserId='" + _operator.UserId + "',ReturnNums='" + item.Nums + "', StatisticsUserName='" + bdata.RealName + "',StatisticsTime=NOW(),StatisticsNums='" + item.Nums + "' where Id='" + item.JobId + "';  ";
                    // update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+" + item.Nums + " where Id=(select ParentId from PB_JobBooking where Id='" + item.JobId + "');
                }

            }

            //单个成品
            if (jobids.Count > 0)
            {
                List<PB_JobBookingQrCode> listdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => jobids.Contains(x.Id)).ToListAsync();
                foreach (var item in listdata)
                {
                    JobMaterial jm = new JobMaterial();
                    jm.JobBookingId = item.Id;
                    jm.JobId = item.ParentId;
                    jm.Nums = 1;
                    jm.MaterialId = item.MaterialId;
                    jm.PackId = "";
                    jm.JobMaterialId = "";
                    materiallist.Add(jm);

                    jobid.Add(item.Id);

                    sqlMain += @" update PB_JobBooking set Status=2,QualityUserId='" + _operator.UserId + "',QualityUserName='" + bdata.RealName + "',QualityTime=NOW(),StatisticsUserId='" + _operator.UserId + "',ReturnNums=IFNULL(ReturnNums,0)+1, StatisticsUserName='" + bdata.RealName + "',StatisticsTime=NOW(),StatisticsNums=IFNULL(StatisticsNums,0)+1 where Id='" + item.ParentId + "';  ";
                    // update PB_ProductionOrderDetail set CompleteNums=IFNULL(CompleteNums,0)+1 where Id=(select ParentId from PB_JobBooking where Id='" + item.ParentId + "');

                    PB_JobNotice jndata = new PB_JobNotice();
                    jndata.Id = IdHelper.GetId();
                    jndata.JobId = item.Id;
                    jndata.NoticeId = dataId;
                    jndata.RecId = recid;
                    jndata.CreatorId = _operator.UserId;
                    jndata.CreateTime = DateTime.Now;
                    jndata.Deleted = false;
                    JobNoticeList.Add(jndata);
                }
            }

            //收货单明细
            var list = materiallist.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Nums) }).ToList();
            foreach (var item in list)
            {
                var Material = materlist.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                TD_RecDetail itemdata = new TD_RecDetail();
                itemdata.Id = IdHelper.GetId();
                itemdata.RecId = recid;
                itemdata.StorId = query.StorId;
                itemdata.MaterialId = item.MaterialId;
                itemdata.Price = Convert.ToDouble(Material.Price);
                itemdata.PlanNum = Convert.ToDouble(item.Nums);
                itemdata.RecNum = Convert.ToDouble(item.Nums);
                itemdata.InNum = 0;
                itemdata.Amount = Convert.ToDouble(item.Nums * Material.Price);
                itemdata.CreateTime = DateTime.Now;
                itemdata.CreatorId = _operator.UserId;
                itemdata.Deleted = false;
                RecDetaillist.Add(itemdata);
                dnuns += item.Nums;
                Amount += Convert.ToDouble(item.Nums * Material.Price);
            }
            //收货单主表
            TD_Receiving recedata = new TD_Receiving();
            recedata.Id = recid;
            recedata.StorId = query.StorId;
            recedata.Code = GetTimeStamp();
            recedata.OrderTime = DateTime.Now;
            recedata.RecTime = DateTime.Now;
            recedata.Type = "Product";
            recedata.RefCode = dataId;
            recedata.Status = 3;
            recedata.TotalNum = Convert.ToDouble(dnuns);
            recedata.InNum = 0;
            recedata.TotalAmt = Convert.ToDouble(Amount);
            recedata.ConfirmUserId = _operator.UserId;
            recedata.ConfirmTime = DateTime.Now;
            recedata.AuditUserId = _operator.UserId;
            recedata.AuditeTime = DateTime.Now;
            recedata.CreatorId = _operator.UserId;
            recedata.CreateTime = DateTime.Now;
            recedata.Deleted = false;
            recedata.QrCode = h_TdRe + "," + recid;
            recedata.DeptId = bdata.DepartmentId;
            recedata.UpdateTime = DateTime.Now;
            recedata.OrderId = "";


            await Db.InsertAsync<PB_JobNotice>(JobNoticeList);

            await Db.InsertAsync<TD_RecDetail>(RecDetaillist);

            await Db.InsertAsync<TD_Receiving>(recedata);

            if (jobid.Count > 0)
            {
                sqlMain += @" update PB_JobBookingQrCode set RecId='" + recid + "' where Id in ('" + string.Join("','", jobid.ToArray()) + "'); ";
                await ExecuteSqlAsync(sqlMain);
            }
        }

        /// <summary>
        /// 打包扫码添加打包明细(非混合包)
        /// </summary>
        /// <param name="qrcode">成品二维码</param>
        /// <param name="packId">包二维码</param>
        /// 优化打包逻辑   2022-03-02   赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task<PB_PackListDetailDTO> GetPackListDetailDataAsync(string qrcode, string packId)
        {
            //获取包的信息
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> selectdata = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                MaterialCode = c.Code,
                PackageNum = c.PackageNum,
                IsNumber = c.IsNumber
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var qdata = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                        join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @selectdata.Invoke(a, b, c);
            var pack = await qdata.Where(x => x.Id == packId.Split(',')[1].ToString()).FirstOrDefaultAsync();
            PB_PackListInfo jobdata = new PB_PackListInfo();
            PB_JobBookingQrCode pbjobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            if (pack != null)
            {
                //获取包明细信息
                List<PB_PackListInfo> listinfo = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                //批量生成包时
                if (pack.PackageType != null)
                {
                    if (pbjobdata != null)
                    {
                        //判断包对应的物料和添加到包里的物料是否一致
                        if (!pack.MaterialId.IsNullOrEmpty())
                        {
                            if (pbjobdata.MaterialId != pack.MaterialId)
                            {
                                throw new BusException("请扫描此包对应的物料");
                            }
                        }
                    }
                    else
                    {
                        throw new BusException("请扫描正确的物料二维码");
                    }
                    //成品是序列号管理
                    if (pack.IsNumber == true)
                    {
                        if (listinfo.Count == pack.Nums)
                        {
                            throw new BusException("已达到包的上限数量");
                        }
                        jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                    }
                    else
                    {
                        jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                    }
                }
                else    //pDA生成包时
                {
                    //成品是序列号管理
                    if (pack.IsNumber != null)
                    {
                        if (pack.IsNumber == true)
                        {
                            if (listinfo.Count == pack.PackageNum)
                            {
                                throw new BusException("已达到包的上限数量");
                            }
                            jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                        }
                        else
                        {
                            jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                        }
                    }
                    else
                    {
                        jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                    }
                }
            }
            if (jobdata == null)
            {
                if (pbjobdata != null)
                {
                    ////查询包明细对应的物料信息
                    //Expression<Func<PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_PackListInfoDTO>> selects = (a, b, c) => new PB_PackListInfoDTO
                    //{
                    //    Code = c.Code,
                    //    MaterialId = c.Id
                    //};
                    //selects = selects.BuildExtendSelectExpre();
                    //var qs = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                    //         join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                    //         from b in ab.DefaultIfEmpty()
                    //         join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                    //         from c in bc.DefaultIfEmpty()
                    //         select @selects.Invoke(a, b, c);
                    //var packdata = await qs.Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                    //if (packdata.Count > 0)
                    //{
                    //    var listdata = packdata.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId }).First();
                    //    if (listdata != null)
                    //    {
                    //        if (listdata.MaterialId != jobbookdata.MaterialId)
                    //        {
                    //            throw new BusException("请扫描相同的物料");
                    //        }
                    //    }
                    //}
                    PB_PackList pbdata = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId.Split(',')[1].ToString()).FirstOrDefaultAsync();
                    if (!pbdata.MaterialId.IsNullOrEmpty())
                    {
                        if (pbjobdata.MaterialId != pbdata.MaterialId)
                        {
                            throw new BusException("请扫描相同的物料");
                        }
                    }

                    Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                    PB_PackListInfo infodata = new PB_PackListInfo();
                    infodata.Id = IdHelper.GetId();
                    infodata.PackId = packId.Split(',')[1].ToString();
                    infodata.JobBookingId = qrcode.Split(',')[1].ToString();
                    infodata.CreatorId = _operator.UserId;
                    infodata.CreatorName = basedata.RealName;
                    infodata.CreatorTime = DateTime.Now;
                    infodata.OldOrNew = pbjobdata.OldOrNew;
                    infodata.Deleted = false;
                    await Db.InsertAsync(infodata);

                    //成品码跟包关联
                    await ExecuteSqlAsync("update PB_JobBookingQrCode set PackId='" + packId.Split(',')[1].ToString() + "' where Id='" + qrcode.Split(',')[1].ToString() + "'");

                    var packinfodata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                    if (packinfodata.Count() == 1)
                    {
                        //生产成品获取物料信息
                        if (!pbjobdata.OrderId.IsNullOrEmpty())
                        {
                            //var orderdetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == pbjobdata.OrderDetailId).FirstOrDefaultAsync();
                            var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == pbjobdata.MaterialId).FirstOrDefaultAsync();
                            int State = 0;
                            if (materialdata.IsNumber == true)
                            {
                                State = 1;
                            }
                            double? nnums = 0;
                            if (materialdata.IsSpec == false)
                            {
                                nnums = materialdata.PackageNum;
                            }
                            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',TaskId='" + pbjobdata.OrderId + "',State=" + State + ",WorkshopId='" + pbjobdata.WorkshopId + "',OldOrNew='" + pbjobdata.OldOrNew + "',Nums='" + nnums + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                            await ExecuteSqlAsync(sqlMain);
                        }
                        else
                        {
                            var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == pbjobdata.MaterialId).FirstOrDefaultAsync();
                            int State = 0;
                            if (materialdata.IsNumber == true)
                            {
                                State = 1;
                            }
                            double? nnums = 0;
                            if (materialdata.IsSpec == false)
                            {
                                nnums = materialdata.PackageNum;
                            }
                            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',State=" + State + ",OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "',Nums='" + nnums + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                            await ExecuteSqlAsync(sqlMain);
                        }

                    }
                    ////成品获取物料信息
                    //Expression<Func<PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_PackListDetailDTO>> select = (a, b, c) => new PB_PackListDetailDTO
                    //{
                    //    MaterialCode = c.Code,
                    //    MaterialSpec = c.Spec,
                    //    MaterialName = c.Name,
                    //    PackListInfoId = a.Id,
                    //    IsNumber = c.IsNumber,
                    //    IsQuantity = c.IsQuantity,
                    //    PackageNum = c.PackageNum,
                    //    IsSpec = c.IsSpec
                    //};
                    //select = select.BuildExtendSelectExpre();
                    //var q = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                    //        join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                    //        from b in ab.DefaultIfEmpty()
                    //        join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                    //        from c in bc.DefaultIfEmpty()
                    //        select @select.Invoke(a, b, c);
                    //q = q.Where(w => w.JobBookingId == qrcode.Split(',')[1].ToString());
                    //PB_PackListDetailDTO data = await q.Where(w => w.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                    PB_PackListDetailDTO data = new PB_PackListDetailDTO();
                    return data;
                }
                else
                {
                    throw new BusException("请扫描或输入正确的物料二维码");
                }
            }
            else
            {
                throw new BusException("成品已存在或已完成打包");
            }
        }

        /// <summary>
        /// PDA扫描第一个成品码后修改包的信息
        /// </summary>
        /// <param name="qrcode">成品二维码</param>
        /// <param name="packId">包二维码</param>
        /// <param name="IsMax">大/小</param>
        /// PDA打包增加选择大小包 2022-02-24 赵锦涛
        /// <returns></returns>
        public async Task UpdatePackListAsync(string qrcode, string packId, Boolean IsMax)
        {
            string jobid = qrcode.Split(',')?[1].ToString();
            string pacid = packId.Split(',')?[1].ToString();
            PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
            PB_Material materdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
            double? nums = 0;
            if (IsMax == true)
            {
                nums = materdata.MaxPackageNum;
            }
            else
            {
                nums = materdata.PackageNum;
            }
            string sqlMain = @" update PB_PackList set Nums=" + nums + " where Id='" + pacid + "'";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 打包扫码添加打包明细(混合包)
        /// </summary>
        /// <param name="qrcode">成品二维码</param>
        /// <param name="packId">包二维码</param>
        /// <returns></returns>
        [Transactional]
        public async Task<PB_PackListDetailDTO> GetBlendPackListDetailDataAsync(string qrcode, string packId)
        {
            PB_PackListInfo jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            if (jobdata == null)
            {
                var jobbookdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == qrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
                if (jobbookdata == null)
                {
                    throw new BusException("请扫描正确的物料二维码");
                }
                var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobbookdata.MaterialId).FirstOrDefaultAsync();
                if (materialdata.IsNumber == false)
                {
                    throw new BusException("此成品不是序列化管理,不能混合打包");
                }
                Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                PB_PackListInfo infodata = new PB_PackListInfo();
                infodata.Id = IdHelper.GetId();
                infodata.PackId = packId.Split(',')[1].ToString();
                infodata.JobBookingId = qrcode.Split(',')[1].ToString();
                infodata.CreatorId = _operator.UserId;
                infodata.CreatorName = basedata.RealName;
                infodata.CreatorTime = DateTime.Now;
                infodata.OldOrNew = jobbookdata.OldOrNew;
                infodata.Deleted = false;
                await Db.InsertAsync(infodata);

                //成品码跟包关联
                await ExecuteSqlAsync("update PB_JobBookingQrCode set PackId='" + packId.Split(',')[1].ToString() + "' where Id='" + qrcode.Split(',')[1].ToString() + "'");

                var packinfodata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                if (packinfodata.Count() == 1)
                {
                    //生产成品获取物料信息
                    if (!jobbookdata.OrderId.IsNullOrEmpty())
                    {
                        var orderdetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == jobbookdata.OrderDetailId).FirstOrDefaultAsync();
                        int State = 0;
                        if (materialdata.IsNumber == true)
                        {
                            State = 1;
                        }
                        string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "(混合)',MaterialId='',TaskId='" + jobbookdata.OrderId + "',State=" + State + ",WorkshopId='" + jobbookdata.WorkshopId + "',OldOrNew='" + jobbookdata.OldOrNew + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                        await ExecuteSqlAsync(sqlMain);
                    }
                    else
                    {
                        //var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobbookdata.MaterialId).FirstOrDefaultAsync();
                        int State = 0;
                        if (materialdata.IsNumber == true)
                        {
                            State = 1;
                        }
                        string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "(混合)',MaterialId='',State=" + State + ",OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                        await ExecuteSqlAsync(sqlMain);
                    }

                }

                //成品获取物料信息
                //Expression<Func<PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_PackListDetailDTO>> select = (a, b, c) => new PB_PackListDetailDTO
                //{
                //    MaterialCode = c.Code,
                //    MaterialSpec = c.Spec,
                //    MaterialName = c.Name,
                //    PackListInfoId = a.Id,
                //    IsNumber = c.IsNumber,
                //    IsQuantity = c.IsQuantity,
                //    PackageNum = c.PackageNum
                //};
                //select = select.BuildExtendSelectExpre();
                //var q = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                //        from b in ab.DefaultIfEmpty()
                //        join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                //        from c in bc.DefaultIfEmpty()
                //        select @select.Invoke(a, b, c);
                //q = q.Where(w => w.JobBookingId == qrcode.Split(',')[1].ToString());
                PB_PackListDetailDTO data = new PB_PackListDetailDTO();
                return data;
            }
            else
            {
                throw new BusException("成品已存在或已完成打包");
            }
        }

        /// <summary>
        /// 打包扫码添加打包明细(混合包)(作废)
        /// </summary>
        /// <param name="qrcode">成品二维码</param>
        /// <param name="packId">包二维码</param>
        /// <returns></returns>
        [Transactional]
        public async Task<PB_PackListDetailDTO> GetPackListDetailAsync(string qrcode, string packId)
        {
            string jobid = qrcode.Split(',')[1].ToString();
            PB_PackListInfo jobdata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.JobBookingId == jobid).FirstOrDefaultAsync();
            if (jobdata == null)
            {
                var jobbookdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                if (jobbookdata == null)
                {
                    throw new BusException("请扫描正确的物料二维码");
                }
                Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                PB_PackListInfo infodata = new PB_PackListInfo();
                infodata.Id = IdHelper.GetId();
                infodata.PackId = packId.Split(',')[1].ToString();
                infodata.JobBookingId = qrcode.Split(',')[1].ToString();
                infodata.CreatorId = _operator.UserId;
                infodata.CreatorName = basedata.RealName;
                infodata.CreatorTime = DateTime.Now;
                infodata.OldOrNew = jobbookdata.OldOrNew;
                infodata.Deleted = false;
                await Db.InsertAsync(infodata);

                //成品码跟包关联
                await ExecuteSqlAsync("update PB_JobBookingQrCode set PackId='" + packId.Split(',')[1].ToString() + "' where Id='" + jobid + "'");

                ////生产成品获取物料信息
                //if (!jobbookdata.OrderId.IsNullOrEmpty())
                //{
                //    List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                //    var jobMdata = joblist.GroupBy(x => new { x.MaterialId, x.MaterialName, x.OldOrNew }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, OldOrNew = x.Key.OldOrNew, JobCount = x.Count() }).ToList();
                //    if (jobMdata.Count == 1)
                //    {
                //        var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobMdata.FirstOrDefault().MaterialId).FirstOrDefaultAsync();
                //        if (materialdata.IsNumber == true)
                //        {
                //            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',TaskId='" + joblist.FirstOrDefault().OrderId + "',State=1,WorkshopId='" + joblist.FirstOrDefault().WorkshopId + "',OldOrNew='" + jobMdata.FirstOrDefault().OldOrNew + "',PackageType=0  where Id='" + packId.Split(',')[1].ToString() + "'";
                //            await ExecuteSqlAsync(sqlMain);
                //        }
                //        else
                //        {
                //            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',TaskId='" + joblist.FirstOrDefault().OrderId + "',State=0,WorkshopId='" + joblist.FirstOrDefault().WorkshopId + "',OldOrNew='" + jobMdata.FirstOrDefault().OldOrNew + "',PackageType=0  where Id='" + packId.Split(',')[1].ToString() + "'";
                //            await ExecuteSqlAsync(sqlMain);
                //        }
                //    }
                //    else
                //    {
                //        string sqlMain = @"update PB_PackList set BoxName='" + jobMdata.FirstOrDefault().MaterialName + "(混合)',MaterialId='',TaskId='" + joblist.FirstOrDefault().OrderId + "',State=1,WorkshopId='" + joblist.FirstOrDefault().WorkshopId + "',OldOrNew='" + jobMdata.FirstOrDefault().OldOrNew + "',PackageType=1  where Id='" + packId.Split(',')[1].ToString() + "'";
                //        await ExecuteSqlAsync(sqlMain);
                //    }

                //    //var orderdetaildata = await Db.GetIQueryable<PB_ProductionOrderDetail>().Where(x => x.Id == jobbookdata.OrderDetailId).FirstOrDefaultAsync();
                //    //int State = 0;
                //    //if (materialdata.IsNumber == true)
                //    //{
                //    //    State = 1;
                //    //}
                //    //string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "(混合)',MaterialId='',TaskId='" + jobbookdata.OrderId + "',State=" + State + ",WorkshopId='" + jobbookdata.WorkshopId + "',OldOrNew='" + jobbookdata.OldOrNew + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                //    //await ExecuteSqlAsync(sqlMain);
                //}
                //else
                //{
                //    List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId.Split(',')[1].ToString()).ToListAsync();
                //    var jobMdata = joblist.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, JobCount = x.Count() }).ToList();
                //    if (jobMdata.Count == 1)
                //    {
                //        var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobMdata.FirstOrDefault().MaterialId).FirstOrDefaultAsync();
                //        if (materialdata.IsNumber == true)
                //        {
                //            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',State=1,OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "',PackageType=0 where Id='" + packId.Split(',')[1].ToString() + "'";
                //            await ExecuteSqlAsync(sqlMain);
                //        }
                //        else
                //        {
                //            string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "',MaterialId='" + materialdata.Id + "',State=0,OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "',PackageType=0 where Id='" + packId.Split(',')[1].ToString() + "'";
                //            await ExecuteSqlAsync(sqlMain);
                //        }
                //    }
                //    else
                //    {
                //        string sqlMain = @"update PB_PackList set BoxName='" + jobMdata.FirstOrDefault().MaterialName + "(混合)',MaterialId='',State=1,OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "',PackageType=0 where Id='" + packId.Split(',')[1].ToString() + "'";
                //        await ExecuteSqlAsync(sqlMain);
                //    }
                //    //var materialdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobbookdata.MaterialId).FirstOrDefaultAsync();
                //    //int State = 0;
                //    //if (materialdata.IsNumber == true)
                //    //{
                //    //    State = 1;
                //    //}
                //    //string sqlMain = @"update PB_PackList set BoxName='" + materialdata.Name + "(混合)',MaterialId='',State=" + State + ",OldOrNew=1,WorkshopId='" + basedata.DepartmentId + "' where Id='" + packId.Split(',')[1].ToString() + "'";
                //    //await ExecuteSqlAsync(sqlMain);
                //}

                PB_PackListDetailDTO data = new PB_PackListDetailDTO();
                return data;
            }
            else
            {
                throw new BusException("成品不存在或已完成打包");
            }
        }

        /// <summary>
        /// 获取包下的明细信息
        /// </summary>
        /// <param name="packId">包二维码</param>
        /// <returns></returns>
        public async Task<PB_PackListDataDTO> GetPackListDataAsync(string packId)
        {
            var deptdata = await _odept.GetOperatorDept();
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> selectdata = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                MaterialCode = c.Code,
                PackageNum = c.PackageNum,
                MaterialSpec = c.Spec
            };
            selectdata = selectdata.BuildExtendSelectExpre();
            var qdata = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                        join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                        from c in ac.DefaultIfEmpty()
                        select @selectdata.Invoke(a, b, c);
            qdata = qdata.Where(x => x.Id == packId.Split(',')[1].ToString());
            var maindata = await qdata.FirstOrDefaultAsync();
            if (maindata != null)
            {
                //获取设计清单成品打包信息
                Expression<Func<PB_JobBookingQrCode, PB_Material, PB_PackListInfo, PackDetailListDTO>> select = (a, b, c) => new PackDetailListDTO
                {
                    PackId = a.PackId,
                    JobBookingId = a.Id,
                    MaterialName = b.Name,
                    SerialNumber = a.SerialNumber,
                    MaterialSpec = b.Spec,
                    PackInfoId = c.Id
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                        join c in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals c.JobBookingId into ac
                        from c in ac.DefaultIfEmpty()
                        select @select.Invoke(a, b, c);
                q = q.Where(w => w.PackId == packId.Split(',')[1].ToString());
                //Expression<Func<PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_PackListDetailDTO>> select = (a, b, c) => new PB_PackListDetailDTO
                //{
                //    MaterialCode = c.Code,
                //    MaterialSpec = c.Spec,
                //    MaterialName = c.Name,
                //    PackListInfoId = a.Id,
                //    IsNumber = c.IsNumber,
                //    IsQuantity = c.IsQuantity,
                //    PackageNum = c.PackageNum,
                //    SerialNumber = b.SerialNumber,
                //    ProductCode = c.ProductCode,
                //    IsProduct = c.IsProduct
                //};
                //select = select.BuildExtendSelectExpre();
                //var q = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                //        join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                //        from b in ab.DefaultIfEmpty()
                //        join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                //        from c in bc.DefaultIfEmpty()
                //        select @select.Invoke(a, b, c);
                //q = q.Where(w => w.PackId == packId.Split(',')[1].ToString());
                var data = await q.ToListAsync();
                PB_PackListDataDTO pbdata = new PB_PackListDataDTO();
                pbdata.Id = maindata.Id;
                pbdata.DeptId = maindata.DeptId;
                pbdata.BoxNo = maindata.BoxNo;
                pbdata.BoxName = maindata.BoxName;
                pbdata.MaterialCode = maindata.MaterialCode;
                pbdata.MaterialSpec = maindata.MaterialSpec;
                pbdata.Status = maindata.Status;
                pbdata.TaskId = maindata.TaskId;
                pbdata.Type = maindata.Type;
                pbdata.Nums = maindata.Nums;
                pbdata.CreateTime = maindata.CreateTime;
                pbdata.NoticeId = maindata.NoticeId;
                pbdata.CreatorId = maindata.CreatorId;
                pbdata.Deleted = maindata.Deleted;
                pbdata.CreatorName = maindata.CreatorName;
                pbdata.QrCode = maindata.QrCode;
                pbdata.DeptIdName = deptdata.DeptName;
                pbdata.State = maindata.State;
                //如果是PC端生成的包信息默认数量根据是否是标准包返回这个包的数量
                pbdata.PackageNum = maindata.PackageType == null ? maindata.PackageNum : maindata.Nums;
                pbdata.MaterialId = maindata.MaterialId;
                pbdata.PackageType = maindata.PackageType;
                pbdata.IsUnpacking = maindata.IsUnpacking;
                pbdata.PackListDetail = data;
                if (data != null)
                {
                    return pbdata;
                }
                else
                {
                    throw new BusException("暂无数据");
                }
            }
            else
            {
                throw new BusException("请扫描正确的包信息");
            }

        }

        public async Task<PageResult<PB_PackListDetailDTO>> GetPackListInfoListDataAsync(PageInput<PackListInfoConditionDTO> input)
        {
            var search = input.Search;
            var where = LinqHelper.True<PB_PackListDetailDTO>();
            Expression<Func<PB_PackListInfo, PB_JobBookingQrCode, PB_Material, PB_PackListDetailDTO>> select = (a, b, c) => new PB_PackListDetailDTO
            {
                MaterialCode = c.Code,
                MaterialSpec = c.Spec,
                MaterialName = c.Name,
                PackListInfoId = a.Id,
                IsNumber = c.IsNumber,
                IsQuantity = c.IsQuantity,
                SerialNumber = b.SerialNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                    join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                        //join c in Db.GetIQueryable<PB_ProductionOrderDetail>() on b.OrderDetailId equals c.Id into ac
                        //from c in ac.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into ad
                    from c in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            if (!search.Keyword.IsNullOrEmpty())
            {
                where = where.And(x => x.JobBookingId.Contains(search.Keyword));
            }
            where = where.And(x => x.PackId == search.packId);
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// PC包明细成品码补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        public async Task PackInfoPrintAsync(PackInfoPrintData data, MongoDBOptions _mongodbOptions)
        {
            var deptdata = await _odept.GetOperatorDept();
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_JobBookingQrCodeDTO>> select = (a, b) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                IsMine = b.IsMine,
                IsStandard = b.IsStandard,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var listdata = await q.Where(x => data.jobqrcodeIds.Contains(x.Id)).ToListAsync();
            if (listdata.Count > 0)
            {
                List<PrintQueue> pqlist = new List<PrintQueue>();
                //推送批次
                string timestamp = Guid.NewGuid().ToString("N");
                foreach (var item in listdata)
                {
                    var sql = "SELECT project.`Name`,buding.Buildingnumber FROM PB_JobBookingQrCode AS job LEFT JOIN PB_ProductionOrder AS orderdata ON job.OrderId = orderdata.Id  LEFT JOIN PB_DesignList AS List ON orderdata.DesignId = List.Id LEFT JOIN PB_Project AS project ON List.ProjectId = project.Id  LEFT JOIN PB_Buildingnumber AS buding ON List.BuildingNumberID = buding.Id WHERE  job.Id = '" + item.Id + "'";
                    List<JobProjectData> JobProjectData = await Db.GetListBySqlAsync<JobProjectData>(sql);
                    PrintQueue pq = new PrintQueue();
                    pq.Id = IdHelper.GetId();
                    pq.No = item.Id + "," + item.SerialNumber;
                    pq.Name = item.MaterialName;
                    pq.TypeName = item.MaterialSpec;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = deptdata.DeptName;
                    pq.QrCode = item.QrCode;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = "0";
                    pq.Printer = data.PrinterId;
                    pq.IsProduct = item.IsProduct;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = listdata.Count();
                    pq.ProjectName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Name;
                    pq.BuildingNumberName = JobProjectData.Count == 0 ? "" : JobProjectData[0].Buildingnumber;
                    pq.IsStandard = item.IsStandard == false ? 0 : 1;
                    pqlist.Add(pq);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, pqlist);
            }
            else
            {
                throw new BusException("请选择后打印");
            }
        }

        public async Task<PB_PackListDTO> UpdatePackListDataAsync(string packId, int nums)
        {
            var deptdata = await _odept.GetOperatorDept();
            int status = 1;
            if (deptdata.DeptType == 2)
            {
                status = 3;
            }
            string id = packId.Split(',')[1].ToString();
            List<PB_PackMaterialCount> PackMaterialCount = new List<PB_PackMaterialCount>();
            List<PB_JobBookingQrCode> joblist = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == id).ToListAsync();
            var jobMdata = joblist.GroupBy(x => new { x.MaterialId, x.MaterialName }).Select(x => new { MaterialId = x.Key.MaterialId, MaterialName = x.Key.MaterialName, Nums = x.Count() }).ToList();
            string sqlMain = string.Empty;
            if (jobMdata.Count == 1)
            {
                sqlMain += @" update PB_PackList set BoxName='" + jobMdata.FirstOrDefault().MaterialName + "',MaterialId='" + jobMdata.FirstOrDefault().MaterialId + "',TaskId='" + joblist.FirstOrDefault().OrderId + "',WorkshopId='" + joblist.FirstOrDefault().WorkshopId + "',OldOrNew='" + joblist.FirstOrDefault().OldOrNew + "',PackageType=0,Status='" + status + "',Nums='" + nums + "'  where Id='" + packId.Split(',')[1].ToString() + "'; ";

                PB_PackMaterialCount PackCount = new PB_PackMaterialCount();
                PackCount.Id = IdHelper.GetId();
                PackCount.PackId = id;
                PackCount.MaterialId = jobMdata.FirstOrDefault().MaterialId;
                PackCount.Nums = nums;
                PackMaterialCount.Add(PackCount);
            }
            else
            {
                sqlMain += @" update PB_PackList set BoxName='" + jobMdata.FirstOrDefault().MaterialName + "(混合)',MaterialId='',TaskId='" + joblist.FirstOrDefault().OrderId + "',WorkshopId='" + joblist.FirstOrDefault().WorkshopId + "',OldOrNew='" + joblist.FirstOrDefault().OldOrNew + "',PackageType=1,Status='" + status + "',Nums='" + nums + "'  where Id='" + packId.Split(',')[1].ToString() + "'; ";

                foreach (var item in jobMdata)
                {
                    PB_PackMaterialCount PackCount = new PB_PackMaterialCount();
                    PackCount.Id = IdHelper.GetId();
                    PackCount.PackId = id;
                    PackCount.MaterialId = jobMdata.FirstOrDefault().MaterialId;
                    PackCount.Nums = item.Nums;
                    PackMaterialCount.Add(PackCount);
                }
            }

            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCount);
            await ExecuteSqlAsync(sqlMain);

            //await ExecuteSqlAsync("update PB_PackList set Status='" + status + "',Nums='" + nums + "' where Id='" + id + "'");
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = deptdata.DeptName,
                MaterialCode = c.Code,
                MaterialSpec = c.Spec
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Where(x => x.Id == id);
            return await q.FirstOrDefaultAsync();
        }

        public async Task<List<PB_PackList>> GetPackListAsync(string userqrcode, int Type)
        {
            var q = GetIQueryable().Where(x => x.CreatorId == userqrcode.Split(',')[1].ToString() && x.Type == Type && (x.Status == 0 || x.Status == 1)).OrderByDescending(x => x.CreateTime);
            return await q.ToListAsync();
        }

        /// <summary>
        /// 通知入库获取完成打包的数据
        /// </summary>
        /// <param name="userqrcode">用户二维码</param>
        /// 优化PDA通知入库列表   2022-03-02   赵锦涛
        /// <returns></returns>
        public async Task<List<PackListWarehousingNoticeDTO>> GetPackListWarehousDataAsync(string userqrcode)
        {
            //if (!string.IsNullOrEmpty(userqrcode))
            //{
            //    return await GetIQueryable().Where(x => x.Status == 1 && _operator.Property.DeptIds.Contains(x.WorkshopId)).OrderByDescending(x=>x.CreateTime).ToListAsync();
            //}
            //else
            //{
            //    return await GetIQueryable().Where(x => x.Status == 1 && _operator.Property.DeptIds.Contains(x.WorkshopId)).OrderByDescending(x => x.CreateTime).ToListAsync();
            //}

            if (_operator.Property?.DeptIds.Count == 0)
            {
                throw new BusException("暂无权限,请联系管理员");
            }

            List<string> strare = _operator.Property?.DeptIds;
            string worksjopid = "";
            foreach (var item in strare)
            {
                worksjopid += "'" + item + "',";
            }
            worksjopid = worksjopid.Substring(0, worksjopid.Length - 1);
            //string sqlMain = @"select a.Id,a.CreateTime,a.BoxName,a.Nums FROM PB_PackList as a join PB_PackListInfo as b on a.Id=b.PackId join PB_JobBookingQrCode as c on b.JobBookingId=c.Id where a.`Status`=1 and IFNULL(c.RecId,'')='' and a.WorkShopId in (" + worksjopid + ")  group by a.Id,a.CreateTime,a.BoxName,a.Nums  order by a.CreateTime desc";
            //string sqlMain = @"select * from (select a.Id,a.CreateTime,a.MaterialId,a.BoxName,a.Nums,'0' as Type,c.OrderId,'' as JobId FROM PB_PackList as a join PB_PackListInfo as b on a.Id=b.PackId join PB_JobBookingQrCode as c on b.JobBookingId=c.Id where a.`Status`=1 and IFNULL(c.RecId,'')='' and a.WorkShopId in (" + worksjopid + ")  group by a.Id,a.CreateTime,a.BoxName,a.Nums,c.OrderId  UNION select a.Id,a.CreateTime,a.MaterialId,b.MaterialName as BoxName,a.Nums,'1' as Type,a.OrderId,'' as JobId from PB_JobMaterial as a join PB_JobBooking as b on a.ParentId=b.Id where a.`Status`=0 and b.WorkShopId in (" + worksjopid + ") )as t order by CreateTime desc";
            string sqlMain = @"select * from (select a.Id,a.CreateTime,a.MaterialId,a.BoxName,a.Nums as MaxNums,a.Nums,'0' as Type,'' OrderId,'' as JobId FROM PB_PackList as a where a.`Status`=1 and a.WorkShopId in (" + worksjopid + ") and a.PackageType=0  group by a.Id,a.CreateTime,a.BoxName,a.Nums  UNION select a.Id,a.CreateTime,'' as MaterialId,a.BoxName,a.Nums as MaxNums,a.Nums,'0' as Type,'' OrderId,'' as JobId FROM PB_PackList as a where a.`Status`=1  and a.WorkShopId in (" + worksjopid + ") and a.PackageType=1  group by a.Id,a.CreateTime,a.BoxName,a.Nums  UNION select a.Id,a.CreateTime,a.MaterialId,b.MaterialName as BoxName,a.Nums as MaxNums,a.Nums,'1' as Type,a.OrderId,'' as JobId from PB_JobMaterial as a join PB_JobBooking as b on a.ParentId=b.Id where a.`Status`=0 and b.WorkShopId in (" + worksjopid + ") )as t order by CreateTime desc";
            List<PackListWarehousingNoticeDTO> listdata = await Db.GetListBySqlAsync<PackListWarehousingNoticeDTO>(sqlMain);
            return listdata;
        }

        /// <summary>
        /// 扫描获取要通知入库的单个成品
        /// </summary>
        /// <param name="JobQrCode">成品二维码</param>
        /// <returns></returns>
        public async Task<PackListWarehousingNoticeDTO> GetJobMaterialDataAsync(string JobQrCode)
        {
            string jobmodel = JobQrCode.Split(',')?[0].ToString();
            if (jobmodel != "14")
            {
                throw new BusException("请扫描正确的成品信息");
            }
            string jobId = JobQrCode.Split(',')?[1].ToString();
            string sqlMain = @"select a.Id,NOW() as CreateTime,a.MaterialId,b.`Name` as BoxName,'1' as Nums,'2' as Type,a.OrderId,a.Id as JobId,a.RecId  from PB_JobBookingQrCode as a left join PB_Material as b on a.MaterialId=b.Id where a.Id='" + jobId + "' and IFNULL(a.PackId,'')='' ";
            List<PackListWarehousingNoticeDTO> listdata = await Db.GetListBySqlAsync<PackListWarehousingNoticeDTO>(sqlMain);
            if (listdata.Count == 0)
            {
                throw new BusException("请扫描未打包的成品码");
            }
            if (!listdata.FirstOrDefault().RecId.IsNullOrEmpty())
            {
                throw new BusException("已通知入库不能重复扫描");
            }
            return listdata.FirstOrDefault();
        }

        public async Task<List<PB_PackList>> GetPackListWarehousDataManualInputAsync(string userqrcode)
        {
            var userInfo = await Db.GetIQueryable<Base_User>().Where(x => x.Id == userqrcode.Split(',')[1].ToString()).FirstOrDefaultAsync();
            return await GetIQueryable().Where(x => x.Status == 1 && _operator.Property.DeptIds.Contains(x.WorkshopId)).OrderByDescending(x => x.CreateTime).ToListAsync();
        }

        public async Task<List<PB_PackList>> GetPackListWarehousStatusManualInputAsync(string ManualInput)
        {
            var userInfo = await Db.GetIQueryable<Base_User>().Where(x => x.UserName == ManualInput.Split(',')[1].ToString()).FirstOrDefaultAsync();
            return await GetIQueryable().Where(x => x.DeptId == userInfo.DepartmentId && x.Status == 2).ToListAsync();
        }


        public async Task<List<PB_PackList>> GetPackListWarehousStatusAsync(string userqrcode)
        {
            if (!string.IsNullOrEmpty(userqrcode))
            {
                return await GetIQueryable().Where(x => x.Id == userqrcode.Split(',')[1].ToString() && x.Status == 2).ToListAsync();
            }
            else
            {
                return await GetIQueryable().Where(x => x.Status == 2).ToListAsync();
            }
            //return await q.;
        }

        /// <summary>
        /// 删除打包明细信息
        /// </summary>
        /// <param name="packinfoId">打包明细Id</param>
        /// <returns></returns>
        public async Task DeletePackListInfoDataAsync(string packinfoId)
        {
            //修改成品表的包Id为NULL
            PB_PackListInfo infodata = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.Id == packinfoId).FirstOrDefaultAsync();
            string sqlMain = @"update PB_JobBookingQrCode set PackId=NULL where Id='" + infodata.JobBookingId + "'";
            await ExecuteSqlAsync(sqlMain);

            await Db.DeleteAsync<PB_PackListInfo>(packinfoId);
        }

        public async Task DeletePackListDataAsync(string packinfoId)
        {
            var q = await Db.GetIQueryable<PB_PackListInfo>().Where(x => x.PackId == packinfoId).ToListAsync();
            if (q.Count() == 0)
            {
                await DeleteAsync(packinfoId);
            }
            else
            {
                throw new BusException("该包下有物料，不允许删除");
            }
        }

        /// <summary>
        /// PC包列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_PackListDTO>> GetDataListPackDto(PageInput<PackListConditionDTO> input)
        {
            var where = LinqHelper.True<PB_PackListDTO>();

            var search = input.Search;
            Expression<Func<PB_PackList, Base_Department, PB_PackListDTO>> select = (a, b) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()

                    select @select.Invoke(a, b);

            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PackListDTO, bool>(
                  ParsingConfig.Default, false, $@"Id.Contains(@0) or BoxName.Contains(@0) or CreatorName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.WarehousStatus.IsNullOrEmpty())
            {
                where = where.And(x => x.Status == Convert.ToInt32(search.WarehousStatus));
            }
            where = where.And(m => m.Type == 1);//包
            where = where.And(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }
        /// <summary>
        /// 批量生产箱码,并推送队列
        /// </summary>
        /// <param name="nums"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task AddrowsAsyne(Print data, MongoDBOptions _mongodbOptions)
        {
            List<PB_PackList> listdata = new List<PB_PackList>();//创建打包集合
            List<PrintQueue> ori = new List<PrintQueue>();
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            var q = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == basedata.DepartmentId).FirstOrDefaultAsync();
            for (int i = 0; i < data.quantity; i++)
            {
                PB_PackList pbdata = new PB_PackList();
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                string sjtime = Convert.ToInt64(ts.TotalSeconds).ToString();
                string dataName = "xm_" + sjtime;
                string dataId = IdHelper.GetId();
                pbdata.Id = dataId;
                pbdata.DeptId = basedata.DepartmentId;
                pbdata.BoxNo = dataName;
                pbdata.QrCode = h_Pack + "," + dataId;
                pbdata.Type = 2;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreateTime = DateTime.Now;
                pbdata.CreatorName = basedata.RealName;
                pbdata.Status = 0;
                listdata.Add(pbdata);

                PrintQueue printdata = new PrintQueue();
                printdata.Id = IdHelper.GetId();
                printdata.No = dataId;
                printdata.Name = "批量生成" + dataName;
                printdata.Date = DateTime.Now.ToString();
                printdata.Dept = q.Name;
                printdata.QrCode = h_Pack + "," + dataId;
                printdata.Type = Skill_Type.Xiang.ToString();
                printdata.Status = "0";
                printdata.Printer = data.PrinterId;
                ori.Add(printdata);

            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, ori);
            await Db.InsertAsync(listdata);
        }

        public async Task<PageResult<PB_PackListDTO>> GetDataListPackDtoXiang(PageInput<PackListConditionDTO> input)
        {
            var where = LinqHelper.True<PB_PackListDTO>();

            var search = input.Search;
            Expression<Func<PB_PackList, Base_Department, PB_ProductionOrder, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                TaskIdName = c.POName,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProductionOrder>() on a.TaskId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);

            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PackListDTO, bool>(
                  ParsingConfig.Default, false, $@"{search.Condition}.Equals(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.WarehousStatus.IsNullOrEmpty())
            {
                where = where.And(x => x.Status == Convert.ToInt32(search.WarehousStatus));
            }
            where = where.And(j => _operator.Property.DeptIds.Contains(j.DeptId));
            where = where.And(m => m.Type == 2);//包
            return await q.Where(where).GetPageResultAsync(input);
        }



        public async Task<List<PB_PackListDTO>> Selectid(string id)
        {

            Expression<Func<PB_PackList, Base_Department, PB_ProductionOrder, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                TaskIdName = c.POName,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProductionOrder>() on a.TaskId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);

            q = q.Where(m => m.Id == id);
            var res = await q.ToListAsync();
            return res;
        }

        public async Task<List<PB_PackListDTO>> Selectids(string ids)
        {
            Expression<Func<PB_PackList, Base_Department, PB_ProductionOrder, PB_Material, PB_PackListDTO>> select = (a, b, c, d) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                TaskIdName = c.POName,
                MaterialName = d.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProductionOrder>() on a.TaskId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            List<string> listdata = new List<string>();
            string[] arr = ids.Split(',');
            foreach (var aa in arr)
            {
                listdata.Add(aa);
            }
            q = q.Where(m => listdata.Contains(m.Id));
            var res = await q.ToListAsync();
            return res;
        }

        /// <summary>
        /// 拆包列表
        /// </summary>
        /// <returns></returns>
        public async Task<PageResult<PB_UnpackingDTO>> GetUnPackingListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            var where = LinqHelper.True<PB_UnpackingDTO>();
            Expression<Func<PB_Unpacking, PB_PackList, PB_PackList, PB_UnpackingDTO>> select = (a, b, c) => new PB_UnpackingDTO
            {
                PrimaryPackName = b.BoxName,
                NewPackName = c.BoxName,
                OperationDate = Convert.ToDateTime(a.CreateTime).ToString("yyyy-MM-dd"),
                DeptId = b.DeptId
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Unpacking>().AsExpandable()
                    join b in Db.GetIQueryable<PB_PackList>() on a.PrimaryPackId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_PackList>() on a.NewPackId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.PrimaryPackName, keyword)
                      || EF.Functions.Like(x.NewPackName, keyword)
                      || EF.Functions.Like(x.OperatorUserName, keyword)
                      || EF.Functions.Like(x.PrimaryPackId, keyword)
                      || EF.Functions.Like(x.NewPackId, keyword));
            }
            q = q.Where(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 拆包明细
        /// </summary>
        /// <param name="ParentId">拆包主表id</param>
        /// <returns></returns>
        public async Task<List<PB_UnpackingDetailDTO>> GetUnPackingDetailListAsync(string ParentId)
        {
            Expression<Func<PB_UnpackingDetail, PB_JobBookingQrCode, PB_Material, PB_UnpackingDetailDTO>> select = (a, b, c) => new PB_UnpackingDetailDTO
            {
                MaterialId = c.Id,
                MaterialCode = c.Code,
                MaterialName = c.Name,
                SerialNumber = b.SerialNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_UnpackingDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Where(x => x.ParentId == ParentId);
            return await q.ToListAsync();
        }

        /// <summary>
        /// 批量生成包码
        /// </summary>
        /// <param name="data">数量</param>
        /// <param name="_mongodbOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        [Transactional]
        public async Task AddBatchPackQrcodeAsync(Print data, MongoDBOptions _mongodbOptions)
        {
            List<PB_PackList> listdata = new List<PB_PackList>();//创建打包集合
            List<PrintQueue> ori = new List<PrintQueue>();
            Base_User basedata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //var q = await Db.GetIQueryable<Base_Department>().Where(m => m.Id == basedata.DepartmentId).FirstOrDefaultAsync();
            var deptdata = await _odept.GetOperatorDept();

            PB_Material materdate = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == data.MaterialId).FirstOrDefaultAsync();

            string timestamp = GetTimeStamp();
            string strguid = Guid.NewGuid().ToString("N");

            for (int i = 0; i < data.quantity; i++)
            {
                PB_PackList pbdata = new PB_PackList();
                string dataName = "bag_" + timestamp;
                string dataId = IdHelper.GetId();
                pbdata.Id = dataId;
                pbdata.DeptId = basedata.DepartmentId;
                pbdata.BoxNo = dataName;
                pbdata.QrCode = h_Pack + "," + dataId;
                pbdata.Type = 1;
                pbdata.CreatorId = _operator.UserId;
                pbdata.CreateTime = DateTime.Now;
                pbdata.CreatorName = basedata.RealName;
                pbdata.Status = 0;
                pbdata.PackageType = data.PackageType;
                pbdata.IsUnpacking = data.IsUnpacking;
                pbdata.MaterialId = data.PackageType == 0 ? data.MaterialId : "";//data传过来的物料id
                if (data.PackageType == 0)
                {
                    pbdata.Nums = data.Nums;
                }
                pbdata.BoxName = data.PackageType == 0 ? data.MaterialIName : data.MaterialIName + "(混合)";
                listdata.Add(pbdata);

                PrintQueue printdata = new PrintQueue();
                printdata.Id = IdHelper.GetId();
                printdata.No = dataId;
                printdata.Name = data.PackageType == 0 ? data.MaterialIName : data.MaterialIName + "(混合)";
                printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                printdata.Dept = deptdata.DeptName;
                printdata.QrCode = h_Pack + "," + dataId;
                printdata.Type = Skill_Type.Package.ToString();
                if (data.PackageType == 0)
                {
                    printdata.Status = data.Nums.ToString();
                }
                printdata.Printer = data.PrinterId;
                printdata.TypeName = materdate.Spec;
                printdata.IsProduct = materdate.IsProduct;
                printdata.Code = materdate.IsProduct == true ? materdate.ProductCode : materdate.Code;
                printdata.BatchNumber = strguid;
                printdata.JobCount = data.quantity;
                ori.Add(printdata);
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, ori);

            await Db.InsertAsync(listdata);
        }

        /// <summary>
        /// 批量重打包码
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// 推送队列增加批次    2022-03-01  赵锦涛
        /// <returns></returns>
        public async Task RetypeBatchPackQrcodeAsync(Print data, MongoDBOptions _mongodbOptions)
        {
            Expression<Func<PB_PackList, Base_Department, PB_Material, PB_PackListDTO>> select = (a, b, c) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                MaterialCode = c.Code,
                IsProduct = c.IsProduct,
                ProductCode = c.ProductCode,
                MaterialSpec = c.Spec
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PackList>().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            List<PB_PackListDTO> listdata = await q.Where(x => data.ids.Contains(x.Id)).ToListAsync();
            var deptdata = await _odept.GetOperatorDept();
            List<PrintQueue> ori = new List<PrintQueue>();
            string timestamp = Guid.NewGuid().ToString("N");
            foreach (var item in listdata)
            {
                PrintQueue printdata = new PrintQueue();
                printdata.Id = IdHelper.GetId();
                printdata.No = item.Id;
                printdata.Name = item.BoxName;
                printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                printdata.Dept = deptdata.DeptName;
                printdata.TypeName = item.MaterialSpec;
                printdata.QrCode = item.QrCode;
                printdata.Type = Skill_Type.Package.ToString();
                printdata.Status = data.Nums.ToString();
                printdata.Printer = data.PrinterId;
                printdata.IsProduct = item.IsProduct == null ? true : item.IsProduct;
                printdata.Status = item.Nums.ToString();
                printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                printdata.BatchNumber = timestamp;
                printdata.JobCount = listdata.Count;
                ori.Add(printdata);
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, ori);
        }

        /// <summary>
        /// 获取操作者法人下的所有仓库
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_Department>> GetDetpListAsync()
        {
            var detpdata = await _odept.GetOperatorDeptFaren();
            List<Base_Department> Departmentdata = await Db.GetIQueryable<Base_Department>().ToListAsync();
            var deptlist = Departmentdata.Where(x => x.ParentId == detpdata.DetpId).ToList();
            List<string> liststr = new List<string>();

            foreach (var item in deptlist)
            {

                liststr.Add(item.Id);

                GetDeptItem(item.Id, liststr, Departmentdata);
            }
            List<Base_Department> listdata = Departmentdata.Where(x => liststr.Contains(x.Id) && x.Type == 2).ToList();
            return listdata;

        }

        /// <summary>
        /// 递归查找公司下所有的仓库
        /// </summary>
        /// <param name="deptId">组织Id</param>
        /// <param name="deptlist">是仓库的集合</param>
        /// <param name="Departmentdata">组织数据</param>
        /// <returns></returns>
        private List<string> GetDeptItem(string deptId, List<string> deptlist, List<Base_Department> Departmentdata)
        {
            var dlist = Departmentdata.Where(x => x.ParentId == deptId).ToList();
            foreach (var item in dlist)
            {
                deptlist.Add(item.Id);
                GetDeptItem(item.Id, deptlist, Departmentdata);
            }
            return deptlist;
        }

        /// <summary>
        /// PDA 包码查询
        /// </summary>
        /// <param name="PackQrCode"></param>
        /// <returns></returns>
        public async Task<List<PB_PackListDTO>> GetPackListQrCode(string PackQrCode)
        {
            string[] qrcodemodel = PackQrCode.Split(',');
            string materialId = string.Empty;
            if (qrcodemodel[0].ToString() == "14")
            {

                materialId = PackQrCode.Split(',')[1].ToString();
                if (materialId == "")
                {
                    throw new BusException("请输入物料编号");
                }
                Expression<Func<PB_PackListInfo, PB_PackList, PB_JobBookingQrCode, IT_LocalDetail, PB_Location, PB_Material, PB_StorArea, PB_Rack,
            PB_PackListDTO>> select3 = (a, b, c, d, e, f, x, z) => new PB_PackListDTO
            {

                MaterialCode = f.Code,
                MaterialName = f.Name,
                JobId = c.Id,
                Id = b.Id,
                Status = b.Status,
                Postiton = x.Name + "/" + z.Name + "/" + e.Name,
                PackageType = b.PackageType,
                BoxName = b.BoxName,
                MaterialSpec = f.Spec,
            };
                select3 = select3.BuildExtendSelectExpre();
                var qres = from a in Db.GetIQueryable<PB_PackListInfo>().AsExpandable()
                           join b in Db.GetIQueryable<PB_PackList>() on a.PackId equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           join c in Db.GetIQueryable<PB_JobBookingQrCode>() on a.JobBookingId equals c.Id into ac
                           from c in ac.DefaultIfEmpty()
                           join d in Db.GetIQueryable<IT_LocalDetail>() on b.Id equals d.PackId into bd
                           from d in bd.DefaultIfEmpty()
                           join e in Db.GetIQueryable<PB_Location>() on d.LocalId equals e.Id into ed
                           from e in ed.DefaultIfEmpty()
                           join f in Db.GetIQueryable<PB_Material>() on c.MaterialId equals f.Id into cf
                           from f in cf.DefaultIfEmpty()
                           join x in Db.GetIQueryable<PB_StorArea>() on e.AreaId equals x.Id into ex
                           from x in ex.DefaultIfEmpty()

                           join z in Db.GetIQueryable<PB_Rack>() on e.RackId equals z.Id into ez
                           from z in ez.DefaultIfEmpty()
                           select @select3.Invoke(a, b, c, d, e, f, x, z);
                qres = qres.Where(x => x.JobId == materialId);

                var res2 = await qres.ToListAsync();
                if (res2.Count <= 0)
                {
                    throw new BusException("物料编号不存在");
                }
                return res2;





                //                Expression<Func<PB_PackList, PB_Material, IT_LocalDetail, PB_Location, PB_Rack, PB_StorArea,Base_UnitItems
                //,PB_PackListInfo,PB_JobBookingQrCode,
                //PB_PackListDTO >> select3 = (a, b, c, d, e, f, g, h,t) => new PB_PackListDTO
                //                {


                //                    MaterialCode = b.Code,
                //                    MaterialName = b.Name,
                //                    MaterialSpec=b.Spec,
                //                    Postiton = f.Name + "/" + e.Name + "/" + d.Name,
                //                    Danwei=g.Name,
                //                   JobId=t.Id,
                //};
                //                select3 = select3.BuildExtendSelectExpre();
                //                var qres= from a in GetIQueryable().AsExpandable()
                //                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                //                        from b in ab.DefaultIfEmpty()
                //                        join c in Db.GetIQueryable<IT_LocalDetail>() on a.Id equals c.PackId into ac
                //                          from c in ac.DefaultIfEmpty()
                //                          join d in Db.GetIQueryable<PB_Location>() on c.LocalId equals d.Id into cd
                //                          from d in cd.DefaultIfEmpty()
                //                          join e in Db.GetIQueryable<PB_Rack>() on d.RackId equals e.Id into de
                //                          from e in de.DefaultIfEmpty()
                //                          join f in Db.GetIQueryable<PB_StorArea>() on d.AreaId equals f.Id into df
                //                          from f in df.DefaultIfEmpty()
                //                          join g in Db.GetIQueryable<Base_UnitItems>() on b.storageId equals g.Id into bg
                //                          from g in bg.DefaultIfEmpty()
                //                          join h in Db.GetIQueryable<PB_PackListInfo>() on a.Id equals h.PackId into ah
                //                          from h in ah.DefaultIfEmpty()
                //                          join t in Db.GetIQueryable<PB_JobBookingQrCode>() on h.JobBookingId equals t.Id into ht
                //                          from t in ht.DefaultIfEmpty()
                //                          select @select3.Invoke(a, b, c, d, e, f, g, h, t);
                //                qres = qres.Where(x => x.JobId == materialId);

                //                var res2 = await qres.ToListAsync();
                //                if (res2.Count<=0) {
                //                    throw new BusException("物料编号不存在");
                //                }
                //                return res2;
            }

            Expression<Func<PB_PackList, Base_Department, PB_ProductionOrder, PB_Material, IT_LocalDetail, PB_Location, PB_Rack, PB_StorArea, PB_PackListDTO>> select = (a, b, c, d, e, f, g, h) => new PB_PackListDTO
            {
                DeptIdName = b.Name,
                TaskIdName = c.POName,
                MaterialCode = d.Code,
                MaterialName = d.Name,
                Postiton = h.Name + "/" + g.Name + "/" + f.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<Base_Department>() on a.DeptId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_ProductionOrder>() on a.TaskId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<IT_LocalDetail>() on a.Id equals e.PackId into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Location>() on e.LocalId equals f.Id into ef
                    from f in ef.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_Rack>() on f.RackId equals g.Id into fg
                    from g in fg.DefaultIfEmpty()
                    join h in Db.GetIQueryable<PB_StorArea>() on f.AreaId equals h.Id into fh
                    from h in fh.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e, f, g, h);
            q = q.Where(x => x.Id == qrcodemodel[1].ToString());

            var res = await q.ToListAsync();
            if (res.Count <= 0)
            {
                throw new BusException("包编号不存在");
            }
            return res;



        }

        /// <summary>
        /// PDA补打包码或者物料码
        /// </summary>
        /// <param name="code">包(物料)Id</param>
        /// <returns></returns>
        public async Task<PrintPackOrMaterialDTO> GetPrintPackOrMaterialDataAsync(string code)
        {
            PrintPackOrMaterialDTO pdata = new PrintPackOrMaterialDTO();
            var deptdata = await _odept.GetOperatorDept();
            string[] model = code.Split(',');
            if (model[0] == "13")
            {
                string packid = model?[1].ToString();
                PB_PackList pack = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packid).FirstOrDefaultAsync();
                if (pack != null)
                {
                    if (!pack.MaterialId.IsNullOrEmpty())
                    {
                        PB_Material itemdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == pack.MaterialId).FirstOrDefaultAsync();
                        pdata.MaterialSpec = itemdata.Spec;
                        pdata.Code = itemdata.IsProduct == true ? itemdata.ProductCode : itemdata.Code;
                    }
                    pdata.DeptIdName = deptdata.DeptName;
                    pdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pdata.Nums = pack.Nums;
                    pdata.QrCode = pack.QrCode;
                    pdata.BoxName = pack.BoxName;
                }
                else
                {
                    throw new BusException("请输入或扫描正确的二维码");
                }
            }
            else if (model[0] == "04")
            {
                string materialId = "";
                if (model.Length > 2)
                {
                    materialId = model?[3].ToString();
                }
                else
                {
                    materialId = model?[1].ToString();
                }
                PB_Material mdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (mdata != null)
                {
                    pdata.DeptIdName = deptdata.DeptName;
                    pdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pdata.QrCode = "04," + mdata.Id;
                    pdata.BoxName = mdata.Name;
                    pdata.MaterialSpec = mdata.Spec;
                    pdata.Code = mdata.IsProduct == true ? mdata.ProductCode : mdata.Code;
                }
                else
                {
                    throw new BusException("请输入或扫描正确的二维码");
                }
            }
            else if (model[0] == "14")
            {
                string jobid = model?[1].ToString();
                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                if (jobdata != null)
                {
                    PB_Material mdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
                    pdata.DeptIdName = deptdata.DeptName;
                    pdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pdata.QrCode = jobdata.QrCode;
                    pdata.BoxName = mdata.Name;
                    pdata.MaterialSpec = mdata.Spec;
                    pdata.Code = mdata.IsProduct == true ? mdata.ProductCode : mdata.Code;
                }
                else
                {
                    throw new BusException("请输入或扫描正确的二维码");
                }
            }
            //PB_PackList pack = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == code).FirstOrDefaultAsync();
            //if (pack != null)
            //{
            //    PB_Material itemdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == pack.MaterialId).FirstOrDefaultAsync();
            //    pdata.DeptIdName = deptdata.DeptName;
            //    pdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
            //    pdata.Nums = pack.Nums;
            //    pdata.QrCode = pack.QrCode;
            //    pdata.BoxName = pack.BoxName;
            //    if (itemdata != null)
            //    {
            //        pdata.MaterialSpec = itemdata.Spec;
            //        pdata.Code = itemdata.IsProduct == true ? itemdata.ProductCode : itemdata.Code;
            //    }
            //}
            //else
            //{
            //    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => (x.Id == code || x.MaterialId == code)).FirstOrDefaultAsync();
            //    if (jobdata != null)
            //    {
            //        PB_Material mdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == jobdata.MaterialId).FirstOrDefaultAsync();
            //        if (mdata != null)
            //        {
            //            pdata.DeptIdName = deptdata.DeptName;
            //            pdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
            //            pdata.QrCode = "04," + mdata.Id;
            //            pdata.BoxName = mdata.Name;
            //            pdata.MaterialSpec = mdata.Spec;
            //            pdata.Code = mdata.IsProduct == true ? mdata.ProductCode : mdata.Code;
            //        }
            //    }
            //}
            if (pdata.QrCode == null)
            {
                throw new BusException("请扫描正确的编码");
            }
            else
            {
                return pdata;
            }
        }



        #endregion

        #region 初始化包数量

        public async Task SavePackMaterialListAsync()
        {
            string sqlMain = @"select PackId,MaterialId,Count(MaterialId) as Nums from PB_JobBookingQrCode where IFNULL(PackId,'')!='' group by PackId,MaterialId";
            var listdata = await Db.GetListBySqlAsync<PackMaterialCount>(sqlMain);
            List<PB_PackMaterialCount> PackMaterialCount = new List<PB_PackMaterialCount>();
            foreach (var item in listdata)
            {
                PB_PackMaterialCount packm = new PB_PackMaterialCount();
                packm.Id = IdHelper.GetId();
                packm.PackId = item.PackId;
                packm.MaterialId = item.MaterialId;
                packm.Nums = Convert.ToDouble(item.Nums);
                PackMaterialCount.Add(packm);
            }
            await Db.InsertAsync<PB_PackMaterialCount>(PackMaterialCount);
        }

        #endregion

        #region 盘点相关包、物料重置
        /// <summary>
        /// 重建包码
        /// </summary>
        /// <param name="strQrCode"></param>
        /// <returns></returns>
        public async Task<PB_PackList> RebuildBagAsync(string strQrCode)
        {
            PB_PackList bag = new PB_PackList();
            if (!strQrCode.IsNullOrEmpty())
            {
                if (!strQrCode.Contains(","))
                {
                    throw new BusException("二维码格式有误，无法识别！");
                }
                var result = await GetEntityAsync(strQrCode.Split(',')[1]);
                if (!result.IsNullOrEmpty())
                {
                    return result;
                }
                //有码
                bag.Id = strQrCode.Split(',')[1];
                bag.DeptId = _operator?.Property.DepartmentId;
                bag.BoxNo = "bag_" + GetTimeStamp();
                bag.BoxName = "";
                bag.MaterialId = "";
                bag.Status = 3;
                bag.TaskId = "";
                bag.Type = 1;
                bag.Nums = 0;
                bag.State = false;
                bag.CreateTime = DateTime.Now;
                bag.NoticeId = "";
                bag.CreatorId = _operator.UserId;
                bag.Deleted = false;
                bag.CreatorName = _operator?.Property.RealName;
                bag.QrCode = strQrCode;
                bag.WorkshopId = _operator?.Property.DepartmentId;
                bag.OldOrNew = null;
                bag.PackageType = null;
                bag.IsUnpacking = false;
                bag.InStorTime = DateTime.Now;
                bag.OutStorTime = null;
                await InsertAsync(bag);
            }
            else
            {
                //无码
                bag.Id = IdHelper.GetId();
                bag.DeptId = _operator?.Property.DepartmentId;
                bag.BoxNo = "bag_" + GetTimeStamp();
                bag.BoxName = "";
                bag.MaterialId = "";
                bag.Status = 3;
                bag.TaskId = "";
                bag.Type = 1;
                bag.Nums = 0;
                bag.State = false;
                bag.CreateTime = DateTime.Now;
                bag.NoticeId = "";
                bag.CreatorId = _operator.UserId;
                bag.Deleted = false;
                bag.CreatorName = _operator?.Property.RealName;
                bag.QrCode = "13," + bag.Id;
                bag.WorkshopId = _operator?.Property.DepartmentId;
                bag.OldOrNew = null;
                bag.PackageType = null;
                bag.IsUnpacking = false;
                bag.InStorTime = DateTime.Now;
                bag.OutStorTime = null;
                await InsertAsync(bag);
            }
            return bag;
        }

        /// <summary>
        /// 重建物料码
        /// </summary>
        /// <param name="input"></param>
        /// <param name="_redisOptions"></param>
        /// /// <returns></returns>
        //[Transactional]
        public async Task<PB_JobBookingQrCode> RebuildMaterialAsync(RebuildMaterialInputDTO input, RedisOptions _redisOptions)
        {
            //if (input.PackId.IsNullOrEmpty()) 
            //{
            //    throw new BusException("请扫描包二维码！");
            //}
            if (input.QrCode.IsNullOrEmpty() && input.MaterialId.IsNullOrEmpty())
            {
                throw new BusException("请选择物料！");
            }
            PB_JobBookingQrCode QrInfo = new PB_JobBookingQrCode();
            //主键ID
            string _id = "";
            //获取物料详情
            var material = await Db.GetEntityAsync<PB_Material>(input.MaterialId);
            #region 获取流水号
            string No = "";
            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            if (RedisSetHelper.Exists("QualityTestingNumber"))
            {
                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                if (redis.GetString("QualityTestingTime") == thedate)
                {
                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                    No = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                }
                else
                {
                    redis.SetString("QualityTestingTime", thedate);
                    redis.SetString("QualityTestingNumber", "1");
                    No = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                }
            }
            else
            {
                redis.SetString("QualityTestingNumber", "0");
            }
            #endregion
            if (!input.QrCode.IsNullOrEmpty())
            {
                #region 有码
                string[] qrArr = input.QrCode.Split(',');
                _id = qrArr[1];
                QrInfo = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(s => s.Id.Equals(qrArr[1])).FirstOrDefaultAsync();
                if (QrInfo.IsNullOrEmpty())
                {
                    if (input.MaterialId.IsNullOrEmpty())
                    {
                        throw new BusException("当前物料不存在，请选择物料！");
                    }
                    await Db.InsertAsync<PB_JobBookingQrCode>(new PB_JobBookingQrCode()
                    {
                        Id = _id,
                        ParentId = "",
                        OrderId = "",
                        OrderDetailId = "",
                        MaterialId = material.Id,
                        MaterialName = material.Name,
                        SerialNumber = No,
                        QrCode = "14," + qrArr[1],
                        WorkshopId = _operator?.Property.DepartmentId,
                        DesignId = "",
                        DesignDetailId = "",
                        RecId = "",
                        OldOrNew = input.OldOrNew,
                        PurchaseId = "",
                        PackId = input.PackId,
                        PackStatus = 0
                    });
                }
                else
                {
                    QrInfo.PackId = input.PackId;
                    await Db.UpdateAsync<PB_JobBookingQrCode>(QrInfo);
                }
                #endregion
            }
            else
            {
                #region 无码
                _id = IdHelper.GetId();
                await Db.InsertAsync<PB_JobBookingQrCode>(new PB_JobBookingQrCode()
                {
                    Id = _id,
                    ParentId = "",
                    OrderId = "",
                    OrderDetailId = "",
                    MaterialId = material.Id,
                    MaterialName = material.Name,
                    SerialNumber = No,
                    QrCode = "14," + _id,
                    WorkshopId = _operator?.Property.DepartmentId,
                    DesignId = "",
                    DesignDetailId = "",
                    RecId = "",
                    OldOrNew = input.OldOrNew,
                    PurchaseId = "",
                    PackId = input.PackId,
                    PackStatus = 0
                });
                #endregion
            }
            #region 更新包状态
            //获取最新物料档案
            var result = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(s => s.Id.Equals(_id)).FirstOrDefaultAsync();
            if (!input.PackId.IsNullOrEmpty())
            {
                //获取包主表详情
                var Bag = await GetEntityAsync(input.PackId.Split(',')[1]);
                PB_PackListInfo Baginfo = await Db.GetIQueryable<PB_PackListInfo>().Where(s => s.JobBookingId.Equals(_id)).FirstOrDefaultAsync();
                //当前包明细不存在
                if (Baginfo.IsNullOrEmpty())
                {
                    //插入包明细表
                    await Db.InsertAsync<PB_PackListInfo>(
                        new PB_PackListInfo()
                        {
                            Id = IdHelper.GetId(),
                            PackId = input.PackId.Split(',')[1],
                            JobBookingId = _id,
                            Deleted = false,
                            CreatorId = _operator.UserId,
                            CreatorName = _operator?.Property.RealName,
                            CreatorTime = DateTime.Now,
                            OldOrNew = input.OldOrNew
                        });
                }
                else
                {
                    //包明细已存在,更新包ID
                    Baginfo.PackId = input.PackId;
                    await Db.UpdateAsync<PB_PackListInfo>(Baginfo);
                }
                //更新包主表信息
                if (Bag.Nums == 0)
                {
                    //如果包是空的
                    Bag.Nums = 1;
                    Bag.MaterialId = input.MaterialId;
                    Bag.BoxName = result.MaterialName;
                    Bag.PackageType = 0;
                    await Db.UpdateAsync<PB_PackList>(Bag);
                }
                else
                {
                    if (Bag.MaterialId.Equals(input.MaterialId))
                    {
                        Bag.Nums = Bag.Nums + 1;
                        await Db.UpdateAsync<PB_PackList>(Bag);
                    }
                    else
                    {
                        if (Bag.PackageType == 1)
                        {
                            Bag.Nums = Bag.Nums + 1;
                            await Db.UpdateAsync<PB_PackList>(Bag);
                        }
                        else
                        {
                            Bag.Nums = Bag.Nums + 1;
                            Bag.MaterialId = "";
                            Bag.BoxName = result.MaterialName + "混合包";
                            Bag.PackageType = 1;
                            await Db.UpdateAsync<PB_PackList>(Bag);
                        }
                    }
                }
            }
            #endregion
            return result;
        }
        /// <summary>
        /// 重建包提交
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task RebuildSubmitAsync(RebuildSubmitInputDTO input)
        {
            //if (input.LocationId.IsNullOrEmpty())
            //{
            //    throw new BusException("请扫描货位！");
            //}
            //if (input.PackId.IsNullOrEmpty())
            //{
            //    throw new BusException("请扫描包码！");
            //}
            ////判断包在库存明细中是否存在
            //var detailList = await Db.GetIQueryable<IT_LocalDetail>().Where(s=>s.PackId.Equals(input.PackId)).ToListAsync();
            ////如果存在直接更新货位ID
            //if (isExist)
            //{
            //    //如果货位一致跳过
            //    if (true)
            //    {

            //    }
            //    //如果货位不一致替换
            //    string sql = "";
            //}
            ////如果不存在插入明细表
            ////更新库存主表
            ////更新包数量表（PB_PackMaterialCount）
        }

        /// <summary>
        /// 物料重置获取物料信息
        /// </summary>
        /// <returns></returns>
        public async Task<JobBookMaterialDTO> GetJobBookMaterialDataAsync(RebuildMaterialInputDTO input)
        {
            if (input.QrCode.IsNullOrEmpty() && input.MaterialId.IsNullOrEmpty())
            {
                throw new BusException("请选择物料！");
            }
            if (!input.QrCode.IsNullOrEmpty() && input.MaterialId.IsNullOrEmpty())
            {
                string jobid = input.QrCode.Split(',')?[1].ToString();
                if (jobid.Length < 19)
                {
                    throw new BusException("请扫描或输入正确的二维码", 1);
                }
                PB_JobBookingQrCode JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobid).FirstOrDefaultAsync();
                if (JobBookingQrCode != null)
                {
                    input.MaterialId = JobBookingQrCode.MaterialId;
                }
                else
                {
                    throw new BusException("物料码不存在,请选择物料生成码");
                }
            }
            //获取物料详情
            var material = await Db.GetEntityAsync<PB_Material>(input.MaterialId);
            JobBookMaterialDTO jobmaterial = new JobBookMaterialDTO();
            jobmaterial.MaterialId = material.Id;
            jobmaterial.MaterialCode = material.Code;
            jobmaterial.MaterialName = material.Name;
            jobmaterial.MaterialSpec = material.Spec;
            jobmaterial.ProductCode = material.ProductCode;
            return jobmaterial;
        }

        /// <summary>
        /// 生成物料码
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_redisOptions"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task SaveMaterialQrCodeAsync(MaterialQrCodeNewDTO data, RedisOptions _redisOptions, MongoDBOptions _mongodbOptions)
        {
            //生成成品码
            List<PB_JobBookingQrCode> JobBookingQrCode = new List<PB_JobBookingQrCode>();
            List<IT_LocalDetail> LocalDetailList = new List<IT_LocalDetail>();
            List<IT_LocalMaterial> LocalMaterialList = new List<IT_LocalMaterial>();
            List<PrintQueue> PrintQueueList = new List<PrintQueue>();
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            string jobcodeId = string.Empty;
            if (!data.QrCode.IsNullOrEmpty())
            {
                jobcodeId = data.QrCode.Split(',')?[1].ToString();
            }

            string locaId = data.LocaQrCode.Split(',')?[1].ToString();
            PB_Location Location = await Db.GetIQueryable<PB_Location>().Where(x => x.Id == locaId).FirstOrDefaultAsync();

            //推送队列物料批次
            string strguid = Guid.NewGuid().ToString("N");
            // 实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);

            var deptdata = await _odept.GetOperatorDept();

            string sqlMain = string.Empty;

            //获取物料信息
            PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == data.JobMaterial.MaterialId).FirstOrDefaultAsync();
            for (int i = 0; i < data.Nums; i++)
            {
                string strnum = string.Empty;
                if (jobcodeId.IsNullOrEmpty())
                {
                    PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                    jobcodeId = IdHelper.GetId();   //成品档案表ID

                    if (Material.IsSingle == true)
                    {
                        jobcodeId = IdHelper.GetId();   //成品档案表ID
                    }
                    if (RedisSetHelper.Exists("QualityTestingNumber"))
                    {
                        string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                        if (redis.GetString("QualityTestingTime") == thedate)
                        {
                            redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            strnum = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                        else
                        {
                            redis.SetString("QualityTestingTime", thedate);
                            redis.SetString("QualityTestingNumber", "1");
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            strnum = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                    }
                    else
                    {
                        redis.SetString("QualityTestingNumber", "0");
                    }
                    jkcode.Id = jobcodeId;
                    jkcode.ParentId = "";
                    jkcode.OrderId = "";
                    jkcode.OrderDetailId = "";
                    if (Material.IsSingle == true)
                    {
                        jkcode.QrCode = h_Material + "," + data.JobMaterial.MaterialId;
                    }
                    else
                    {
                        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                    }
                    jkcode.MaterialId = data.JobMaterial.MaterialId;
                    jkcode.MaterialName = data.JobMaterial.MaterialName;
                    jkcode.OldOrNew = 1;
                    jkcode.WorkshopId = userdata.FactoryId;
                    jkcode.RecId = "";
                    jkcode.PackId = "";
                    jkcode.PackStatus = 1;
                    JobBookingQrCode.Add(jkcode);
                }

                //成品码推送
                PrintQueue materprint = new PrintQueue();
                materprint.Id = IdHelper.GetId();
                materprint.No = jobcodeId + "," + strnum;
                materprint.Name = data.JobMaterial.MaterialName;
                materprint.TypeName = data.JobMaterial.MaterialSpec;
                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                materprint.Dept = deptdata.DeptName;
                if (Material.IsSingle == true)
                {
                    materprint.QrCode = h_Material + "," + data.JobMaterial.MaterialId;
                }
                else
                {
                    materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                }
                materprint.Type = Skill_Type.Statistics.ToString();
                materprint.Status = "0";
                materprint.Printer = data.PrintId;
                materprint.IsProduct = Material.IsProduct;
                materprint.Code = Material.IsProduct == true ? Material.ProductCode : Material.Code;
                materprint.BatchNumber = strguid;
                materprint.JobCount = data.Nums;
                materprint.ProjectName = "";
                materprint.BuildingNumberName = "";
                materprint.IsStandard = Material.IsStandard == false ? 0 : 1;
                PrintQueueList.Add(materprint);

                PB_JobBookingQrCode JobBookingdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobcodeId).FirstOrDefaultAsync();
                if (!JobBookingdata.IsNullOrEmpty())
                {
                    if (JobBookingdata.PackId.IsNullOrEmpty())
                    {
                        IT_LocalDetail LocalDetaildata = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == jobcodeId).FirstOrDefaultAsync();
                        if (LocalDetaildata.IsNullOrEmpty())
                        {
                            IT_LocalDetail LocalDetail = new IT_LocalDetail();
                            LocalDetail.Id = IdHelper.GetId();
                            LocalDetail.StorId = Location.StorId;
                            LocalDetail.LocalId = locaId;
                            LocalDetail.MaterialId = data.JobMaterial.MaterialId;
                            if (Material.IsSingle == true)
                            {
                                LocalDetail.BarCode = h_Material + "," + data.JobMaterial.MaterialId;
                                LocalDetail.JobId = "";
                            }
                            else
                            {
                                LocalDetail.BarCode = h_FinishedProduct + "," + jobcodeId;
                                LocalDetail.JobId = jobcodeId;
                            }
                            LocalDetail.InTime = DateTime.Now;
                            LocalDetail.CreateTime = DateTime.Now;
                            LocalDetail.CreatorId = _operator.UserId;
                            LocalDetail.Deleted = false;
                            LocalDetail.Num = 1;
                            LocalDetail.PackId = "";
                            LocalDetail.OldOrNew = 1;
                            LocalDetail.RecId = "";
                            LocalDetailList.Add(LocalDetail);
                        }
                    }
                }
                jobcodeId = "";
            }

            var materialdetail = LocalDetailList.GroupBy(x => new { x.StorId, x.LocalId, x.MaterialId }).Select(x => new { StorId = x.Key.StorId, LocalId = x.Key.LocalId, MaterialId = x.Key.MaterialId, Nums = x.Sum(i => i.Num) }).FirstOrDefault();
            if (!materialdetail.IsNullOrEmpty())
            {
                IT_LocalMaterial LocalMaterial = await Db.GetIQueryable<IT_LocalMaterial>().Where(x => x.LocalId == materialdetail.LocalId && x.MaterialId == materialdetail.MaterialId).FirstOrDefaultAsync();
                if (!LocalMaterial.IsNullOrEmpty())
                {
                    sqlMain += @" update  IT_LocalMaterial set Nums_N=IFNULL(Nums_N,0)+" + materialdetail.Nums + ",ScanNum=IFNULL(ScanNum,0)+" + materialdetail.Nums + " where LocalId='" + materialdetail.LocalId + "' and  MaterialId='" + materialdetail.MaterialId + "'; ";
                }
                else
                {
                    IT_LocalMaterial material = new IT_LocalMaterial();
                    material.Id = IdHelper.GetId();
                    material.MaterialId = materialdetail.MaterialId;
                    material.StorId = materialdetail.StorId;
                    material.LocalId = materialdetail.LocalId;
                    material.Nums_N = Convert.ToDouble(materialdetail.Nums);
                    material.Nums_O = 0;
                    material.Nums_R = 0;
                    material.CreatorId = _operator.UserId;
                    material.CreateTime = DateTime.Now;
                    material.Deleted = false;
                    material.AreaId = Location.AreaId;
                    material.RackId = Location.RackId;
                    material.ScanNum = Convert.ToDouble(materialdetail.Nums);
                    material.CheckNum = 0;
                    LocalMaterialList.Add(material);
                }
            }

            if (!sqlMain.IsNullOrEmpty())
            {
                await Db.ExecuteSqlAsync(sqlMain);
            }

            await Db.InsertAsync<IT_LocalDetail>(LocalDetailList);

            await Db.InsertAsync<IT_LocalMaterial>(LocalMaterialList);

            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, PrintQueueList);
            //插入成品码信息
            await Db.InsertAsync<PB_JobBookingQrCode>(JobBookingQrCode);
        }


        #endregion

        #region 查询包信息或者物料信息

        /// <summary>
        /// 查询包信息或者物料信息
        /// </summary>
        /// <param name="QrCode">二维码</param>
        /// <returns></returns>
        public async Task<Object> GetPackOrMaterialDataAsync(string QrCode)
        {
            string pmmodel = QrCode.Split(',')?[0].ToString();
            //包Id
            string packId = string.Empty;
            //物料Id
            string materialId = string.Empty;
            //成品Id
            string jobId = string.Empty;
            if (pmmodel == "13")
            {
                packId = QrCode.Split(',')?[1].ToString();
            }
            else if (pmmodel == "04")
            {
                var model = QrCode.Split(',');
                if (model.Length > 2)
                {
                    materialId = model?[3].ToString();
                }
                else
                {
                    materialId = model?[1].ToString();
                }
            }
            else if (pmmodel == "14")
            {
                jobId = QrCode.Split(',')?[1].ToString();
            }
            var deptdata = await _odept.GetOperatorDept();
            PackModelDTO pdata = new PackModelDTO();
            PrintPackOrMaterialDTO pormdata = new PrintPackOrMaterialDTO();
            if (pmmodel == "13")
            {
                //查询包档案
                PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == packId).FirstOrDefaultAsync();
                if (PackList != null)
                {
                    if (PackList.Status == 5)
                    {
                        throw new BusException("包码已作废");
                    }
                    pdata.Type = 1;
                    pdata.PackId = packId;
                    pdata.BoxName = PackList.BoxName;
                    pdata.PackTypeName = PackList.PackageType == 0 ? "标准包" : "混合包";
                    if (PackList.Status == 3)
                    {
                        pdata.Status = "已入库";
                        IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == packId).FirstOrDefaultAsync();
                        if (LocalDetail != null)
                        {
                            View_StorAreaRackLocation stordata = await Db.GetIQueryable<View_StorAreaRackLocation>().Where(x => x.Id == LocalDetail.LocalId).FirstOrDefaultAsync();
                            pdata.LocaName = stordata == null ? "" : stordata.StorAreaName;
                        }
                    }
                    else
                    {
                        pdata.Status = "已出库";
                    }
                    pdata.Nums = PackList.Nums;
                    PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.PackId == packId).FirstOrDefaultAsync();
                    if (jobdata != null)
                    {
                        if (!jobdata.OrderId.IsNullOrEmpty())
                        {
                            PB_ProductionOrder order = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == jobdata.OrderId).FirstOrDefaultAsync();
                            if (order != null)
                            {
                                if (!order.DesignId.IsNullOrEmpty())
                                {
                                    PB_DesignList DesignList = await Db.GetIQueryable<PB_DesignList>().Where(x => x.Id == order.DesignId).FirstOrDefaultAsync();
                                    pdata.ProjectName = DesignList == null ? "" : DesignList.ProjectName;
                                }
                            }
                        }
                    }
                    if (pdata.ProjectName.IsNullOrEmpty() && pdata.Status == "已出库")
                    {
                        pdata.OutStock = "其他出库";
                    }
                    if (!PackList.MaterialId.IsNullOrEmpty())
                    {
                        PB_Material itemdata = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == PackList.MaterialId).FirstOrDefaultAsync();
                        pormdata.MaterialSpec = itemdata.Spec;
                        pormdata.Code = itemdata.IsProduct == true ? itemdata.ProductCode : itemdata.Code;
                    }
                    pormdata.DeptIdName = deptdata.DeptName;
                    pormdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pormdata.Nums = PackList.Nums;
                    pormdata.QrCode = PackList.QrCode;
                    pormdata.BoxName = PackList.BoxName;
                    pdata.PackOrMaterial = pormdata;
                }
                else
                {
                    throw new BusException("请扫描正确二维码");
                }
            }
            else if (pmmodel == "04")
            {
                PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == materialId).FirstOrDefaultAsync();
                if (Material != null)
                {
                    pdata.Type = 2;
                    pdata.PackTypeName = "单件物料";
                    pdata.BoxName = Material.Name;
                    pdata.PackId = materialId;
                    string sqlMain = @"select a.MaterialId,b.StorAreaName,SUM(a.Num) as Nums from IT_LocalDetail as a
left join View_StorAreaRackLocation as b on a.LocalId=b.Id 
where a.MaterialId='" + materialId + "' group by a.MaterialId,b.StorAreaName";
                    List<LocaMaterialListDTO> listdata = await Db.GetListBySqlAsync<LocaMaterialListDTO>(sqlMain);
                    List<MaterialLocaList> MLocaList = new List<MaterialLocaList>();
                    foreach (var item in listdata)
                    {
                        MaterialLocaList mll = new MaterialLocaList();
                        mll.StorAreaName = item.StorAreaName;
                        mll.Nums = item.Nums;
                        MLocaList.Add(mll);
                    }
                    pdata.MaterialList = MLocaList;

                    pormdata.DeptIdName = deptdata.DeptName;
                    pormdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pormdata.QrCode = "04," + Material.Id;
                    pormdata.BoxName = Material.Name;
                    pormdata.MaterialSpec = Material.Spec;
                    pormdata.Code = Material.IsProduct == true ? Material.ProductCode : Material.Code;
                    pdata.PackOrMaterial = pormdata;
                }
                else
                {
                    throw new BusException("请扫描正确二维码");
                }
            }
            else if (pmmodel == "14")
            {
                //查询成品信息
                PB_JobBookingQrCode JobBookingQrCode = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == jobId).FirstOrDefaultAsync();
                if (JobBookingQrCode != null)
                {
                    if (JobBookingQrCode.PackStatus == 1)
                    {
                        throw new BusException("成品码已作废");
                    }
                    //查询成品对应的物料信息
                    PB_Material Material = await Db.GetIQueryable<PB_Material>().Where(x => x.Id == JobBookingQrCode.MaterialId).FirstOrDefaultAsync();
                    pdata.BoxName = Material.Name;
                    pdata.PackId = jobId;
                    //判断成品是否在包内：否
                    if (JobBookingQrCode.PackId.IsNullOrEmpty())
                    {
                        //查询库内成品信息
                        IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.JobId == jobId).FirstOrDefaultAsync();
                        if (LocalDetail != null)
                        {
                            pdata.Status = "已入库";
                            //查询货位信息
                            View_StorAreaRackLocation stordata = await Db.GetIQueryable<View_StorAreaRackLocation>().Where(x => x.Id == LocalDetail.LocalId).FirstOrDefaultAsync();
                            List<MaterialLocaList> MLocaList = new List<MaterialLocaList>();
                            MaterialLocaList mll = new MaterialLocaList();
                            mll.StorAreaName = stordata.StorAreaName;
                            mll.Nums = LocalDetail.Num;
                            MLocaList.Add(mll);
                            pdata.MaterialList = MLocaList;
                        }
                        else
                        {
                            pdata.Status = "已出库";
                        }
                    }
                    else
                    {
                        //成品在包内
                        PB_PackList PackList = await Db.GetIQueryable<PB_PackList>().Where(x => x.Id == JobBookingQrCode.PackId).FirstOrDefaultAsync();
                        //包在库内
                        if (PackList.Status == 3)
                        {
                            //查询库内信息
                            IT_LocalDetail LocalDetail = await Db.GetIQueryable<IT_LocalDetail>().Where(x => x.PackId == JobBookingQrCode.PackId).FirstOrDefaultAsync();
                            if (LocalDetail != null)
                            {
                                pdata.Status = "已入库";
                                View_StorAreaRackLocation stordata = await Db.GetIQueryable<View_StorAreaRackLocation>().Where(x => x.Id == LocalDetail.LocalId).FirstOrDefaultAsync();
                                List<MaterialLocaList> MLocaList = new List<MaterialLocaList>();
                                MaterialLocaList mll = new MaterialLocaList();
                                mll.StorAreaName = stordata.StorAreaName;
                                mll.Nums = 1;
                                MLocaList.Add(mll);
                                pdata.MaterialList = MLocaList;
                            }
                        }
                        else
                        {
                            pdata.Status = "已出库";
                        }
                    }
                    //查询项目信息
                    if (!JobBookingQrCode.OrderId.IsNullOrEmpty())
                    {
                        PB_ProductionOrder order = await Db.GetIQueryable<PB_ProductionOrder>().Where(x => x.Id == JobBookingQrCode.OrderId).FirstOrDefaultAsync();
                        if (order != null)
                        {
                            if (!order.DesignId.IsNullOrEmpty())
                            {
                                PB_DesignList DesignList = await Db.GetIQueryable<PB_DesignList>().Where(x => x.Id == order.DesignId).FirstOrDefaultAsync();
                                pdata.ProjectName = DesignList == null ? "" : DesignList.ProjectName;
                            }
                        }
                    }
                    pdata.Type = 3;
                    pdata.PackTypeName = "成品码";
                    if (pdata.ProjectName.IsNullOrEmpty() && pdata.Status == "已出库")
                    {
                        pdata.OutStock = "其他出库";
                    }

                    pormdata.DeptIdName = deptdata.DeptName;
                    pormdata.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                    pormdata.QrCode = "04," + Material.Id;
                    pormdata.BoxName = Material.Name;
                    pormdata.MaterialSpec = Material.Spec;
                    pormdata.Code = Material.IsProduct == true ? Material.ProductCode : Material.Code;
                    pdata.PackOrMaterial = pormdata;

                }
                else
                {
                    throw new BusException("请扫描正确二维码");
                }
            }
            return pdata;
        }

        #endregion

        #region 私有成员

        #endregion

        #region 装车与备货条码验证
        public async Task<PageResult<ScanningCode>> GetscanningCodes(PageInput<IT_LocalDetailDtolistContionDTO> input, string PaickmainId)
        {
            //获取备货单数据


            string sql = "SELECT  * FROM (SELECT  loadlist.Nums StockQuantity,loadlist.PackId 'Code','包' AS 'Type', detail.PackId 'transportbillCode',  mater.`Code` 'MaterCode',  mater.`Name` 'MaterName',  mater.`Spec` 'MaterSpec', IFNULL(detail.PackNums, 0) PackNums FROM  pb_unloadlist AS loadlist JOIN(SELECT Id FROM pb_pickuplist WHERE ParentId = '" + PaickmainId+ "') AS picklist ON loadlist.ParentID = picklist.Id LEFT JOIN pb_transportbilldetail AS detail ON detail.PackId = loadlist.PackId  LEFT JOIN pb_material AS mater ON loadlist.MaterialId = mater.Id WHERE loadlist.PackId != '' UNION ALL SELECT 	loadlist.Nums StockQuantity,loadlist.JobId 'Code', '成品' AS 'Type',  detail.JobId 'transportbillCode', mater.`Code` 'MaterCode',  mater.`Name` 'MaterName', mater.`Spec` 'MaterSpec',IFNULL(detail.PackNums, 0) PackNums FROM  pb_unloadlist AS loadlist  JOIN(SELECT Id FROM pb_pickuplist WHERE ParentId = '" + PaickmainId+ "') AS picklist ON loadlist.ParentID = picklist.Id LEFT JOIN pb_transportbilldetail AS detail ON detail.JobId = loadlist.JobId  LEFT JOIN pb_material AS mater ON loadlist.MaterialId = mater.Id WHERE  loadlist.JobId != '' UNION ALL SELECT 	loadlist.Nums StockQuantity,loadlist.MaterialId 'Code', '单个物料' AS 'Type',  detail.MaterialId 'transportbillCode',  mater.`Code` 'MaterCode',  mater.`Name` 'MaterName',  mater.`Spec` 'MaterSpec',  IFNULL(detail.PackNums, 0) PackNums FROM  pb_unloadlist AS loadlist JOIN(SELECT Id, ParentId FROM pb_pickuplist WHERE ParentId = '" + PaickmainId+ "') AS picklist ON loadlist.ParentID = picklist.Id    LEFT JOIN pb_transportbilldetail AS detail ON detail.PreparationNoteId = picklist.ParentId AND detail.MaterialId = loadlist.MaterialId  LEFT JOIN pb_material AS mater ON loadlist.MaterialId = mater.Id  WHERE  loadlist.JobId = ''  AND loadlist.PackId = '' ) AS Duibi ORDER BY Duibi.MaterName";
            var list = await Db.GetListBySqlAsync<ScanningCode>(sql);


            #region   分页处理数据   有bug 没有按照主数据进行处理
            int pagecount;//总页数
            List<ScanningCode> listpro_down = list.ToList();//一个要分页的，类型数据集合，存储的是所有的数据
            List<ScanningCode> productes = new List<ScanningCode>();//用来存储要展示的数据
            int pagees = listpro_down.Count;//所有数据的总条数
                                            //计算总页数
            if (pagees % input.PageRows == 0)
            {
                pagecount = pagees / input.PageRows;
            }
            else
            {
                pagecount = (pagees / input.PageRows) + 1;
            }
            productes = listpro_down.Skip((input.PageIndex - 1) * input.PageRows).Take(input.PageRows).ToList();//分页的重点
            return new PageResult<ScanningCode> { Data = productes, Total = pagees };
            #endregion



        }

        public async Task<PackListDetailDto> GetPackDetail(string QrCode)
        {
            string code = QrCode.Split(',')[0].ToString();
            if (code == "13")
            {
                //获取包id
                string PackId= QrCode.Split(',')[1].ToString();
                Expression<Func<PB_PackList, PB_Material, PackListDetailDto>> select = (a, b) => new PackListDetailDto
                {
                 MaterCode=b.Code,
                 MaterSpec=b.Spec,
                };
                select = select.BuildExtendSelectExpre();
                var q = from a in GetIQueryable().AsExpandable()
                        join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                        from b in ab.DefaultIfEmpty()
                       
                        select @select.Invoke(a, b);
               var data= await q.Where(x => x.Id == PackId).FirstOrDefaultAsync();
                return data;

            }
            else {
                return null;
            }
           

        }





        #endregion
    }
}